PHP循环搜索字符串,如果不匹配则执行

cka*_*man 2 php

我试图在更大的字符串中搜索多个字符串,如果它们都不匹配,则操纵原始字符串.这是代码:

$searchthis = 'this is a string'
$arr = array('foo', 'bar');
foreach ($arr as &$value) {
  if (strpos($searchthis, $value) !== false) {
    break;
  }
  else{
    $searchthis = $searchthis . ' addthis';
  }
}
Run Code Online (Sandbox Code Playgroud)

问题是在搜索第一个字符串变量并且不匹配之后,在运行下一个测试之前操纵原始搜索字符串.

有什么想法吗?提前致谢

Tim*_*per 6

你需要检查你的循环之外是否有匹配.您可以通过在找到至少一个字符串时设置变量($found)来完成此操作true:

$found = false;
foreach ($arr as &$value) {
  if (strpos($searchthis, $value) !== false) {
    $found = true;
  }
}
if (!$found) {
  $searchthis = $searchthis . ' addthis'; 
}
Run Code Online (Sandbox Code Playgroud)