正则表达式作为explode()中的分隔符(Regular expression as delimiter in explode())

编程入门 行业动态 更新时间:2024-10-27 00:28:35
正则表达式作为explode()中的分隔符(Regular expression as delimiter in explode())

所以我有一个字符串,我正在变成一个数组,但我想用正则表达式分隔每个单词。 我使用下面的函数匹配整个单词。

function substr_count_array($haystack, $needle) { $initial = 0; $bits = explode(' ', $haystack); foreach ($needle as $substring) { if (!in_array($substring, $bits)) { continue; } $initial += substr_count($haystack, $substring); } return $initial; }

问题是它匹配字符串animal ,但不是animals 。 如果我做这样的部分匹配:

function substr_count_array2($haystack, $needle) { $initial = 0; foreach ($needle as $substring) { $initial += substr_count($haystack, $substring); } return $initial; }

它也匹配,比方说,因为它包含了animals一词并返回2 。 我如何使用正则表达式作为分隔符来explode()以便我可以匹配每个长度为5-7个字符的字符串?

简单解释一下:

$animals = array('cat','dog','bird'); $toString = implode(' ', $animals); $data = array('a'); echo substr_count_array($toString, $data);

如果我搜索诸如a之类的字符,它会通过检查并将其验证为合法值,因为a包含在第一个元素中。 但是如果我匹配整个空间爆炸的单词,如果它们没有被空格隔开,它就会省略它们。 因此,我需要用一个正则表达式来分隔,该正则表达式匹配要匹配的字符串之后的任何内容。

So I have a string which I'm turning into an array but I want to separate each word using a regex. I'm matching a whole word using the below function.

function substr_count_array($haystack, $needle) { $initial = 0; $bits = explode(' ', $haystack); foreach ($needle as $substring) { if (!in_array($substring, $bits)) { continue; } $initial += substr_count($haystack, $substring); } return $initial; }

The problem is that it matches the string animal for example but not animals. And if I do a partial match like this:

function substr_count_array2($haystack, $needle) { $initial = 0; foreach ($needle as $substring) { $initial += substr_count($haystack, $substring); } return $initial; }

It also matches, let's say, a since it's contained withing the word animals and returns 2. How do I explode() using a regular expression as a delimiter so that I may, for example, match every string that has a length of 5-7 characters?

Explained simpler:

$animals = array('cat','dog','bird'); $toString = implode(' ', $animals); $data = array('a'); echo substr_count_array($toString, $data);

If I search for a character such as a, it gets through the check and validates as a legit value because a is contained within the first element. But if I match whole words exploded by a space, it omits them if they are not separated by a space. Thus, I need to separate with a regular expression that matches anything AFTER the string that is to be matched.

更多推荐

本文发布于:2023-08-07 07:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1462014.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分隔符   正则表达式   explode   delimiter   Regular

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!