PHP中的preg_replace函数
我正在使用PHP中的preg_replace函数,php,Php,我正在使用preg\u replace函数删除停止字列表。目前,我有一个数组,其中包含lst个停止字。作为preg\u replace的参数,我使用它作为第一个参数(即,preg\u replace(^$stopwordlist$,'',$string),正如您所看到的,我也使用^$,因为我需要精确匹配word。但是我得到了以下错误 syntax error, unexpected '^', expecting ')' in 语法错误,中出现意外的“^”,应为“') 谢谢如果您想精确匹配单词,则
preg\u replace
函数删除停止字列表。目前,我有一个数组,其中包含lst个停止字。作为preg\u replace
的参数,我使用它作为第一个参数(即,preg\u replace(^$stopwordlist$,'',$string)
,正如您所看到的,我也使用^$
,因为我需要精确匹配word。但是我得到了以下错误
syntax error, unexpected '^', expecting ')' in
语法错误,中出现意外的“^”,应为“')
谢谢如果您想精确匹配单词,则REG EXP和
preg_replace
不是您需要的
查看str\u replace
或strtrt
文档,找出您需要的文档
如果
$stopwordlist
是一个数组,您可能需要首先将其删除
至于语法错误,您需要将^
和$
放在引号中,您的正则表达式中也缺少分隔符
将代码更改为以下内容:
// Implode with a |, which is basically an 'or' statement is regex
$pattern = '/^' . implode('|', $stopwordlist) . '$/';
// Replace them
$replaced = preg_replace($pattern, '', $string);
如果您需要一个地方来测试正则表达式,请尝试。您可以使用
$string=str_replace($stopwordlist, "", $string);
需要字符串、正则表达式分隔符。请在此处发布您的代码。您是否学习过PHP的基础知识?请从@user1926567开始,如果您使用此代码
preg_replace('/^.$stopwordlist'$/'、'.$string)
^和$不像您认为的那样工作,该怎么办。如果$string的整个值与传递给它的值相匹配,那么在开头包含^,在结尾包含$string,实际上是要替换它。在$stopwordlist
数组中的每个元素前后都放置一个空格,并去掉^and$