Reputation:
I have an array with words like
$arr = array("go", "walk", ...)
I would like to replace these words with links f they are matched in sentences. But it should be only if they match exactly (for example "walk" should match "Walk" or "walk!" but not also "walking")
And the replacement should be a simple link like: < a href='#walk' >walk< /a >
Anybody Any idea?
Upvotes: 6
Views: 12538
Reputation: 455132
Try something like this:
$words = array('walk','talk');
foreach($words as $word)
{
$word = preg_replace("/\b$word\b/","< a href='#$word' >$word< /a >",$word);
}
Upvotes: 3
Reputation: 239302
function magicWords($words, $string) {
$from = $to = array();
foreach($words as $word) {
$from[] = "/\b$word\b/i"; // \b represents a word boundary
$to[] = '<a href="#' . strtolower($word) . '">${0}</a>';
}
return preg_replace($from, $to, $string);
}
$words = array('go', 'walk');
echo magicWords($words, "Lets go walking on a Walk");
This outputs:
'Lets <a href="#go">go</a> walking on a <a href="#walk">Walk</a>.'
Note that it matches "go", and "walk", but not "walking", and maintains the capital W on Walk while the link becomes lower case "#walk".
This way, "Walk walk WALK wALk" will all link to #walk without affecting the original formatting.
Upvotes: 4
Reputation: 305
I think the following might be what you want.
<?php
$someText = 'I don\'t like walking, I go';
$words = array('walk', 'go');
$regex = '/\\b((' . implode('|',$words) . ')\\b(!|,|\\.|\\?)?)/i';
echo preg_replace_callback(
$regex,
function($matches) {
return '<a href=\'' . strtolower($matches[2]) . '\'>' . $matches[1] . '</a>';
},
$someText);
?>
A few of points though:
Upvotes: 1
Reputation: 5463
Your examples are quite specific, so it's hard to know exactly what you need to match in practice (e.g. do you want to include the '!' in the link?), but try this:
<?php
$text = "Walk! I went for a walk today. I like going walking. Let's go walk!";
$needles = array('go', 'walk');
foreach ($needles as $needle)
$text = preg_replace('/\b(' . $needle . ')\b/i', '<a href="#' . $needle . '">$1</a>', $text);
print $text;
Upvotes: 0
Reputation: 123841
To Match each words like "walk" but not "walking" Use \b for word bounday.
For Example, "\bwalk\b"
Upvotes: 9