Reputation: 29
I am trying to find certain words in a string and replace them with links to pages
I have three arrays which are like this (this is just an example not the actual thing :P)
$string = "Oranges apples pears Pears <p>oranges</p>";
$keyword = array('apples', 'pears', 'oranges');
$links = array('<a href="apples.php">Apples</a>', '<a href="pears.php">Pears</a>', '<a href="oranges.php">Oranges</a>');
$content = str_replace($keyword, $links, $string);
echo $content;
It replaces some of the words but not all of them, that is because there are spaces infront of some words and at the end of some words and some are capitalised etc.
I was wondering what is the best way to achieve what I am trying to do. I also tried preg_replace but I am not too good with regex.
Upvotes: 0
Views: 714
Reputation: 6889
Simply use str_ireplace:
$string = "Oranges apples pears Pears <p>oranges</p>";
$keyword = array('apples', 'pears', 'oranges');
$links = array('<a href="apples.php">Apples</a>', '<a href="pears.php">Pears</a>', '<a href="oranges.php">Oranges</a>');
$content = str_ireplace($keyword, $links, $string);
echo $content;
There should be no problem with spaces. for str_replace it doesn't if there is a space before/after the search term or not.
If you only want to replace whole words then you need to use an regular expression:
$string = "Oranges apples pear Pears <p>oranges</p>";
$keyword = array('apples', 'pear', 'oranges'); // note: "pear" instead of "pears"
$links = array('<a href="apples.php">Apples</a>', '<a href="pears.php">Pears</a>', '<a href="oranges.php">Oranges</a>');
$content = preg_replace(array_map(function($element) {
$element = preg_quote($element);
return "/\b{$element}\b/i";
}, $keyword), $links, $string);
echo $content;
Upvotes: 1
Reputation: 504
You should use str_ireplace function - it is not case-sensitive variant of str_replace function
Upvotes: 0