2017-08-12 51 views
-1

我有代碼查找文本目前符合需要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; 
    } 

這樣簡單地匹配包含文本的任何一句話。但我想要它做的是匹配一個通配符,所以它可以檢測句型。因此,例如它可以檢測到:

​​

希望這是可以理解的。它還需要匹配句子中出現的文本的位置,並通過在開始和結束處添加*來標記它。

回答

1

可以使用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