2013-02-19 28 views
3

我想這樣做,以便如果從$hello輸入$words它們被替換爲bonjour但它不起作用。我該如何去做這件事?我如何讓替換工作,因爲我打算在PHP中?

代碼:

<?php 
$words = $_POST['words']; 
$hello = array('hello', 'hi', 'yo', 'sup'); 
$words = preg_replace('/\b'.$hello.'\b/i', '<span class="highlight">Bonjour</span>', $words); 
echo $words; 
?> 
+2

你試圖使用'$ hello'作爲一個字符串,如果它是一個數組:你雖然可以破滅這一點,有點像!我建議在[php bible](http://php.net)中尋找'for'和'foreach'。 – Dale 2013-02-19 13:18:23

回答

0

你必須如果傳遞的模式陣列,以preg_replace

$hello = array('/\bhello\b/i', '/\bhi\b/i', '/\byo\b/i', '/\bsup\b/i'); 

或單一模式,通過,即決定:

'/\b('.join('|', $hello).')\b/i' 

你當前傳遞的是一個字符串像這樣:

'/\bArray\b/i' 
2

您正在傳遞一個數組到您的模式,它應該是一個字符串。

$words = 'Hello world'; 
$hello = array('hello', 'hi', 'yo', 'sup'); 
$words = preg_replace('/\b('.implode('|', $hello).')\b/i', '<span class="highlight">Bonjour</span>', $words); 
echo $words; 
+0

你應該在'implode'返回的值附近添加括號。否則,它將像'(\ bhello)|(hi)|(yo)|(sup \ b)'那樣工作,這不是所期望的。 – 2013-02-19 13:44:35

+0

斑點!我將編輯我的答案:-) – juco 2013-02-19 13:46:38

0
$words = "Would you like to say hi to him?"; 
$hello = array('hello', 'hi', 'yo', 'sup'); 
$pattern = ""; 
foreach ($hello as $h) 
{ 
    if ($pattern != "") $pattern = $pattern . "|"; 
    $pattern = $pattern . preg_quote ($h); 
} 
$words = preg_replace ('/\b(' . $pattern . ')\b/i', 'Bonjour', $words); 
相關問題