如何让我的替换工作,因为我打算用PHP?

时间:2013-02-19 13:16:47

标签: php regex preg-replace

我想这样做,以便如果在$hello中输入$words中的字词,则会将其替换为 bonjour ,但它不起作用。我到底该怎么做呢?

代码:

<?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;
?>

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

您必须决定是否将一组模式传递给preg_replace

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

或单一模式,即 OR

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

您目前传递的内容是这样的字符串:

'/\bArray\b/i'

答案 2 :(得分: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);