Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:使用preg_match搜索字符串中的子字符串?_Php_Search_Preg Match_Substring - Fatal编程技术网

PHP:使用preg_match搜索字符串中的子字符串?

PHP:使用preg_match搜索字符串中的子字符串?,php,search,preg-match,substring,Php,Search,Preg Match,Substring,我试图创建一个函数来检查php中字符串中的子字符串 public static function stringCheck ($string, $substring) { $patern = "/".$substring."/"; if (preg_match($substring, string) { return true; } else return false; } 但是如果我输入一个在preg_match^.[$|*+?{中使用的特殊字符,搜索就会出错 我尝试

我试图创建一个函数来检查php中字符串中的子字符串

public static function stringCheck ($string, $substring) {
  $patern = "/".$substring."/";

  if (preg_match($substring, string) {
    return true;
  }
  else return false;
}
但是如果我输入一个在preg_match^.[$|*+?{中使用的特殊字符,搜索就会出错

我尝试了下面的代码,但没有成功

$speicalChar = '/(\^|\.|\[|\$|\(|\)|\*|\+|\?|\{|\\)/';
任何人都有preg_match的解决方案或替代方案。请记住,我也希望能够检查符号。我尝试使用strstr,但符号有问题

谢谢你

$pattern = '/' . preg_quote($substring, '/') . '/';
这会为您转义特殊字符。同时传入“/”,因此它也会被转义,因为您将它用作分隔符

另一件事,修复了if条件中的一些输入错误:

if (preg_match($pattern, $string)) {

有什么理由要使用preg_match吗?它必须是正则表达式吗?怎么办

返回haystack字符串中第一个出现的指针的数字位置

如果您没有理由使用正则表达式,请不要使用它们

更新:

关于public static的评论:不要创建类来收集函数,看起来你在这里这么做。这没有意义。只需创建普通函数并将其包含在脚本中。使用类来实现真正的OOP。
Btw.,你应该为你的函数考虑一个更富表现力的名字。String Cuffy非常模糊,它检查了什么?

1,它不是$PARTURN,它的$式样。2,你忘记了一个$,它不是如果PrggMatl $ $子串,它是如果PrggMateMatk $模式,$string和你不需要其他,它可以基本上是:如果PREGGL匹配$模式,$String {true true;}return false;因为如果条件为true,则返回值将为true end这将停止函数,否则它将返回false并停止函数。或者返回bool preg_match$pattern,$string;这不是我的实际代码,我只是写了一个简单的示例来说明语法错误。谢谢,我主要想知道如何检查speical Characters非常感谢boltclock!preg_quote正是我要找的=]@stereofrog:嗯,我刚刚复制了OPs方法签名。别怪我!;:D@stereofrog:你是怎么弄到这么漂亮的圆形浮子的?
public static function stringCheck ($string, $substring) {
  return (strpos($string, $substring) !== false);
}