需要PHP正则表达式的专家 - 字符串内,但使用通配符

需要PHP正则表达式的专家 - 字符串内,但使用通配符

问题描述:

我有代码查找文本目前符合需要PHP正则表达式的专家 - 字符串内,但使用通配符

$data=["as much as I like oranges, I like bananas better", 
"there's no rest for the wicked", 
"the further I move from my target, the further I get", 
"just because I like that song, does not mean I will buy it"]; 

if (stripos($data[1], 'just because I') !== false) { 
     $line=str_ireplace('just because I','*'.just because I.'*',$data[1]); 
     break; 
    } 

这样简单地匹配包含文本的任何一句话。但我想要它做的是匹配一个通配符,所以它可以检测句型。因此,例如它可以检测到:

​​

希望这是可以理解的。它还需要匹配句子中出现的文本的位置,并通过在开始和结束处添加*来标记它。

可以使用preg_replace代替str_ireplace

$data = ["as much as I like oranges, I like bananas better", 
     "there's no rest for the wicked", 
     "the further I move from my target, the further I get", 
     "just because I like that song, does not mean I will buy it", 
     "the further I move from my target, the further I get"]; 
$pattern = '/(.*)(just because I .* does not mean)(.*)/i'; 
$replacement = '$1*$2*$3'; 
foreach ($data as $data_) { 
    $line = preg_replace($pattern, $replacement, $data_, -1, $count)."\n"; 
    if ($count > 0) { 
    break; 
    } 
} 
echo $line; 

返回结果:

*just because I like that song, does not mean* I will buy it 

count变量将包含由更换的次数,按文档。我添加了它,因为它看起来像你想在第一次替换之后跳出循环。

+0

绝对完美。非常感谢。 – Hasen