Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/294.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_Regex - Fatal编程技术网

PHP preg_match使用正则表达式匹配单词

PHP preg_match使用正则表达式匹配单词,php,regex,Php,Regex,我想找到所有使用PHP和正则表达式的演示词 $input ='demo'; $pattern = ''; //$input can be used along with regex, please help here $text = 'This is dem*#o text, contains de12mo3 text, is .demo23* text' if(preg_match($pattern, $text)) { echo 'found'; }else{ echo'not f

我想找到所有使用PHP和正则表达式的演示词

$input ='demo';
$pattern = ''; //$input can be used along with regex, please help here 
$text = 'This is dem*#o text, contains de12mo3 text, is .demo23* text' 

if(preg_match($pattern, $text))
{
 echo 'found';
}else{
 echo'not found';
}
文本中的搜索词演示可能采用以下格式

1) may start with special characters/numbers Eg. "12*demo"
2) may contain special characters/numbers within the word Eg.  "de12*mo"
3) may end with special characters/numbers Eg. "demo12*"
请帮帮我,我卡住了, 提前谢谢


注意:$input的最大长度为15

可能没有效率;但你可以用这个:

/*d.*e.*m.*o.*i


这将匹配任何东西。

可能效率不高;但你可以用这个:

/*d.*e.*m.*o.*i

这将匹配任何内容。

解决方案 我首先从字符串中删除所有特殊字符和数字,然后使用单词边界匹配单词:

$cleaned = preg_replace('/[^a-z ]+/i', '', 'This is dem*#o text, contains de12mo3 text, is .demo23* text');

preg_match_all('/\bdemo\b/i', $cleaned, $matches, PREG_OFFSET_CAPTURE);

var_dump($matches);
将为您提供:

解释 第一行将替换字符串中与/[a-z]+/i匹配的名为subject参数的任何字符,基本上删除了这些字符。正则表达式匹配除字母a-z或空格以外的任何字符或字符组。i标志告诉regex搜索应该不区分大小写,这样我们就不用编写a-zA-Z了

下一行用于匹配单词“demo”。然而,你可以用任何一个词来代替

新正则表达式技术 解决方案 我首先从字符串中删除所有特殊字符和数字,然后使用单词边界匹配单词:

$cleaned = preg_replace('/[^a-z ]+/i', '', 'This is dem*#o text, contains de12mo3 text, is .demo23* text');

preg_match_all('/\bdemo\b/i', $cleaned, $matches, PREG_OFFSET_CAPTURE);

var_dump($matches);
将为您提供:

解释 第一行将替换字符串中与/[a-z]+/i匹配的名为subject参数的任何字符,基本上删除了这些字符。正则表达式匹配除字母a-z或空格以外的任何字符或字符组。i标志告诉regex搜索应该不区分大小写,这样我们就不用编写a-zA-Z了

下一行用于匹配单词“demo”。然而,你可以用任何一个词来代替

新正则表达式技术 在演示字符之间匹配除a-z以外的任何内容


在演示字符之间匹配除a-z以外的任何字符

@PhpMyCoder我对RegEx不熟悉,这是我正在尝试的/[\W$demo\W]/,但问题是,它无法检测word中存在的特殊字符,例如de123*@pcdhan很好,您尝试了一些东西,请确保下次将其放入问题中。@AlexLunix,我的错误,下次不会重复。@PhpMyCoder我对RegEx不熟悉,这是我正在尝试的/[\W$demo\W]/,但问题是,它无法检测word中存在的特殊字符,例如de123*@pcdhan很好,您尝试了一些东西,请确保下次将其放入问题中。@AlexLunix,我的错误,下次不会重复。谢谢@flec,$input的最大长度可以是15个字符。使用strlen检查后向sthanks@flec的长度,$input的最大长度可以是15个字符。使用strlen检查长度afterwards@pcdhan如果您在实施过程中需要任何帮助,请告诉我们。成功实施,再次非常感谢,它确实帮助了我。@pcdhan随时。如果这回答了您的问题,您应该单击旁边的复选标记将其标记为已解决。@pcdhan如果在实施过程中需要任何帮助,请告知我们。成功实施,再次非常感谢,这确实对我有帮助。@pcdhan任何时候都可以。如果这回答了您的问题,您应该单击旁边的复选标记将其标记为已解决。
/\b[^a-z]*d[^a-z]*e[^a-z]*m[^a-z]*o[^a-z]*\b/i