我有一个字符串像
一些用于测试的文本,需要使用php
用正则表达式替换我们也有多余的句子
我需要替换单词regex
之前的句子
我需要一个
的结果使用php
我们也有多余的句子
用""
代替some text for test and need to replace by regex
PHP可以使用'K
使用这个简单的正则表达式:
(?s)^.*?regex'K.*
看演示。
-
(?s)
允许点跨几行匹配。 -
^
断言我们在字符串的开头。 -
.*?regex
惰性匹配直到regex
-
'K
告诉引擎"保留"到目前为止它在返回的匹配中匹配的所有内容(删除它) -
.*
匹配其他所有内容。
在PHP中不需要替换。正如这个php演示的输出所示,您只需匹配:
$mystring = "some text for test and need to replace by regex using php.
We have another sentence";
$regex = '~(?s)^.*?regex'K.*~';
if (preg_match($regex, $mystring, $m)) {
$yourmatch = $m[0];
echo $yourmatch;
}
如果你有任何问题,请告诉我。:) 您不需要正则表达式。您可以使用 substr () 和大小写敏感():
$str = substr($str, strpos($str, 'regex') + 6);
<<p> 看到演示/strong> 下面的正则表达式将只匹配紧跟在字符串regex
之后的字符,
/(?<=regex's)(.*)/s
演示你的PHP代码应该是,
<?php
$mystring = "some text for test and need to replace by regex using php.
We have another sentence";
$regex = '~(?s)(?<=regex's)(.*)~';
if (preg_match($regex, $mystring, $m)) {
$yourmatch = $m[0];
echo $yourmatch;
}
?>
输出:using php.
We have another sentence
解释:
(?s) # Allows . to match anything(including newlines)
(?<=regex's)(.*) # Positive lookbehind is used. It matches anything after the string regex followed by a space.