简体   繁体   English

检查子字符串是否包含在实际字符串的任何位置

[英]Check if substring is contained anywhere in the actual string

I have the following string: 我有以下字符串:

$str = "A string".

When I use: 当我使用时:

preg_match("/A string/", $str)

I get the match everything works perfectly fine, but I want to use the same regular expression for another string: 我得到了匹配,一切工作都很好,但是我想对另一个字符串使用相同的正则表达式:

$str2 = "A test string".

For this case I can use: 对于这种情况,我可以使用:

"/A (test  )?string/"

But I want it to be more complex, it should also be able to match strings like this, for example: 但我希望它更复杂,它也应该能够匹配这样的字符串,例如:

A sttest ring
test A string

I mean that the substring "test " can appear anywhere in the subject. 我的意思是子字符串“ test”可以出现在主题的任何地方。

Is it even possible to find a regular expression for this? 甚至可以为此找到正则表达式吗?

You could try something like this 你可以尝试这样的事情

$str = "My test String";
    if (strpos($str, 'test') !== false) {
        echo 'true';
    }

Try this: 尝试这个:

$str = "A sttest ring";
$newstr = preg_replace("/\s*test\s*/", "", $str);
preg_match("/A string/", $newstr, $matches);
echo $matches ? 'true' : 'false';

Online Demo 在线演示

I would create a function for that: 我将为此创建一个函数:

function containsLetters($testString, $lettersString, $caseSensitive = false, $whiteSpaces = false){
  if(!$caseSensitive){
    $testString = strtolower($testString); $lettersString = strtolower($lettersString);
  }
  if($whiteSpaces){
    $tw = $testString; $lw = $lettersString;
  }
  else{
    $tw = preg_replace('/\s/', '', $testString); $lw = preg_replace('/\s/', '', $lettersString);
  }
  $tst  = str_split($tw); $ltr = str_split($lw); $c = count($ltr); $r = array();
  foreach($ltr as $l){
    foreach($tst as $i => $t){
      if($l === $t){
        $a = array_splice($tst, $i, 1); $r[] = $a[0];
      }
    }
  }
  if(count($r) >= $c){
    return true;
  }
  return false;
}
$test = containsLetters('A sttest ring', 'a test string');

Just pass true to the 3rd argument to make it case sensitive. 只需将true传递给第3个参数以使其区分大小写即可。 Also, pass true to the 4th argument to compare white spaces. 另外,将true传递给第4个参数以比较空白。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM