好的,所以我试图检测某个字符串是否在另一个字符串中,我已经尝试过使用explode
但是由于显而易见的原因它没有工作,只是为了让你可以变得更好我想要完成什么的想法,看看我尝试使用explode
试图解决我的问题的失败尝试
$stringExample1 = "hi, this is a example";
$stringExample2 = "hello again, hi, this is a example, hello again";
$expString = explode($stringExample1, $stringExample2);
if(isset($expString[1]))
{
//$stringExample1 is within $stringExample2 !!
}
else
{
//$stringExample1 is not within $stringExample2 :(
}
感谢任何帮助
答案 0 :(得分:2)
此处strpos
和strstr
失败,因为您在第二个字符串中的example2
中有额外的逗号。我们可以使用正则表达式进行字符串匹配。例如,请参阅以下代码段。
<?php
$str1 = "hi, this is a example";
$str2 = "hello again, hi, this is a example, hello again";
$pattern = "/$str1/";
preg_match_all($pattern, $str2, $matches);
print_r($matches);
输出
Array
(
[0] => Array
(
[0] => hi, this is a example
)
)
如果输出数组的计数($matches
)大于0,那么我们得到匹配,否则我们没有匹配。您可能需要调整$pattern
中创建的正则表达式以满足您的需要,并且可能还需要进行优化。
请告诉我们这是否适合您。
答案 1 :(得分:1)
尝试strpos
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>
答案 2 :(得分:1)