3

我想这样做,如果$hello输入了 from 的话,$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;
?>
4

3 回答 3

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;
于 2013-02-19T13:19:46.280 回答
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'
于 2013-02-19T13:19:16.323 回答
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);
于 2013-02-19T13:21:14.620 回答