How do I get the replacement to work as I intend in PHP?
I want to make it so that if words from are $hello
entered in $words
, they are replaced with bonjour , but that doesn't work. How exactly will I do this?
code:
<?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
source to share
3 answers
You are passing an array to your template, it should be a string. You can hack this, but something like:
$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;
+2
source to share
You will need to decide if you are passing an array of templates to preg_replace
$hello = array('/\bhello\b/i', '/\bhi\b/i', '/\byo\b/i', '/\bsup\b/i');
or one template, i.e. OR :
'/\b('.join('|', $hello).')\b/i'
What you are currently going through is a line like this:
'/\bArray\b/i'
0
source to share
$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);
0
source to share