在php中搜索数组中的子字符串
我正在尝试搜索字符串中某些单词的出现并将它们与数组中的短列表进行匹配。我将通过一个例子来解释我的问题。
$arrTitle = explode(" ", "Suburban Apartments");
foreach( $arrTitle as $key => $value){
echo "Name: $key, Age: $value <br />";
$words = array("hotel", "apart", "hostel");
if (in_array($value, $words)) {
echo "Exists";
}
}
我希望将上面示例中的字符串的一部分“Apartments”与 $words 数组进行比较,以查找字符串“Apart”的出现情况。 我希望这是有道理的。这有可能吗?
谢谢
I'm trying to search for the occurrence of certain words in a string and match them with a short list in an array. I'll explain my question by means of an example.
$arrTitle = explode(" ", "Suburban Apartments");
foreach( $arrTitle as $key => $value){
echo "Name: $key, Age: $value <br />";
$words = array("hotel", "apart", "hostel");
if (in_array($value, $words)) {
echo "Exists";
}
}
I wish to compare a part of the string, in the above example 'Apartments' against the $words array for the occurrence of the string 'Apart'ments.
I hope this makes sense. Is this possible at all?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
然后你必须稍微改变一下你的代码。请看下面的内容:
注意要搜索的单词上添加的 foreach 以及 strpos 的 in_array 替换。
对于您的个人信息,in_array 检查 $word 是否作为整个值存在于数组中,这不是您想要的。您需要使用 strpos 或 stripos (不区分大小写)检查每个单词是否存在...
Then you'll have to change a bit your code. Look at this below:
Note the added foreach on the words to search and the in_array replacement for strpos.
For your personnal information, in_array checks if the $word is in the array as a whole value, which is not what you wanted. You need to check for the existence of each word using strpos or stripos (case insensitive)...
使用正则表达式来匹配文本。
http://php.net/manual/en/function.preg-match.php
您需要一次循环遍历每个要查找的数组值,因此您必须在循环内循环并对每个值运行正则表达式来查找匹配项。
确保它们不区分大小写。
Use regular expressions to match the text.
http://php.net/manual/en/function.preg-match.php
You'll need to cycle through each of your sought array values one at a time so you'll have to loop inside your loop and run the regexp on each one looking for a match.
Make sure to make them case insensitive.