Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.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
通过web表单将正则表达式特殊字符传递给PHP正则表达式_Php_Regex - Fatal编程技术网

通过web表单将正则表达式特殊字符传递给PHP正则表达式

通过web表单将正则表达式特殊字符传递给PHP正则表达式,php,regex,Php,Regex,我有一个web表单,它具有搜索替换功能 表单输入通过preg\u quote传递。那很好,直到现在 现在我想允许用户输入*(星号)通配符preg_quote将其转义。我如何允许它通过并正确应用它 $find = ',*'; // I want to match a comma and all characters after the comma $replace = ''; // replace with empty string $find = preg

我有一个web表单,它具有搜索替换功能

表单输入通过
preg\u quote
传递。那很好,直到现在

现在我想允许用户输入
*
(星号)通配符
preg_quote
将其转义。我如何允许它通过并正确应用它

$find = ',*'; // I want to match a comma and all characters after the comma
$replace = ''; // replace with empty string
                    $find = preg_quote($find_replace[0],'~'); // $find == ',\*';. I want * to remain unescaped. Is replacing "\*" with "*" the best way?
                    if(strpos($find,'\\*') !== false) { // UPDATE: I tried that, and it does work.
                    // $find == ',\*'
                    $find = str_replace('\\*','*',$find);
                    // $find == ',*' -- seems like it should work but doesn't               
                }

                    $value = trim(preg_replace('~' . $find . '~i',$replace,$value));
编辑: 我在上面添加了代码,在
*
前面去掉转义斜杠。它正在工作

使用
$value='Hey,Hey,Hey'
我以'
嘿嘿
'结束。 正如正则表达式模式
,*
(贪婪匹配?)所预期的那样,所有逗号都被删除

注意,在我的代码中,我将使用
$find=str\u replace(“\\*”、“.*”、$find)
$find=str\u replace(“\\*”、“[\s\s]*”、$find)
复制Microsoft Excel的查找/替换功能。

我不知道更好的方法(不认为有任何…),但是一种方法是在
preg_quote
函数调用之后删除星号前的反斜杠:

$find = str_replace("\\*", "*", $find);

这不起作用。它导致像“嘿,嘿,嘿,嘿”这样的文本变成了“嘿,嘿,嘿”。有什么想法吗?事实上,这确实有效。我的问题是,我试图复制Excel的功能来进行*匹配,但我忘记了正则表达式的工作原理有点不同。谢谢您是否知道,*不是“逗号及其后所有字符”的正则表达式?这里的
*
表示“前面字符的任意数量”或“任意数量的逗号”@Gareth谢谢。是的,大约一分钟前,当我刷新我的记忆时,我现在意识到了这一点。大脑衰退。因此,是的,该模式在bwoebi的解决方案中发挥了应有的作用。但是现在我只需要更改为code,这样当用户输入
,*
时,它会匹配逗号后面的所有内容。我正试图在一个web应用程序中复制Excel样式的“查找替换”。@Gareth,我花了一分钟的时间在谷歌上搜索才找到它。这项工作:
$find=str\u replace(“\\*”、“.*”、$find)
复制Excel功能。但也许不完全如此。Excel可能与换行符匹配,但这种模式不匹配。这个答案中的解决方案可能适用于以下情况:(
$find=str\u replace(“\\\*”、“[\s\s]*”、$find)