Ericki
Ericki

Reputation: 119

Search for words in text, and replace them

I'm having a hard time finding the solution to my problem.

I have an array like this in a variable:

$myarray = Array (
[0] => Orange
[1] => Black
[2] => White
[3] => Yellow
[4] => Red
);

Basically, I need search the words of the array in the string, and replace them with the same ones, but with links.

For example, from:

$string = "My content contains orange and also blue";

To:

$string = "My content contains <a href="www.domain.com/orange">orange</a> and also blue";

Upvotes: 1

Views: 93

Answers (3)

user7090116
user7090116

Reputation:

Use str_ireplace and do it using arrays:

$from = array(
    "Orange",
    "Black",
    "White",
    "Yellow",
    "Red"
);

$to = array(
    '<a href="www.domain.com/orange">orange</a> ',
    '<a href="www.domain.com/black">black</a>',
    '<a href="www.domain.com/white">white</a>',
    '<a href="www.domain.com/yellow">yellow</a>',
    '<a href="www.domain.com/red">red</a>'
);

$string = str_ireplace($from, $to, $string);

Edit 1: This also replaces all strings if they are met inside the array, meaning that if you have orange and black in the string, those two will get replaced.

Upvotes: 2

Boopathi D
Boopathi D

Reputation: 377

You can use str_ireplace, check the link

$string = "My content contains orange and also black";
$string = str_ireplace("orange","<a href='http://www.example.com/orange'>orange</a>",$string);

EDIT

As @Ericki has edited the question, please use the below code to achieve the same,

$myarray = array (
'Orange','Black','White','Yellow','Red'
);
$string = "My content contains Orange, Black, Yellow, Red";

foreach($myarray as $item){
    if (strpos($string, $item)) {
        $string = str_ireplace($item,"<a href='http://www.example.com/".$item."'>$item</a>",$string);
    }
}   
var_dump($string);

Upvotes: -1

Nick
Nick

Reputation: 147146

This is probably best achieved using preg_replace. We can create a regex by using implode to create an alternation of each of the words in $myarray; capture that word in a group and then use it in the replacement to add the link around it:

$string = "My content contains orange and also blue in a blackout";

$string = preg_replace('/\b(' . implode('|', $myarray) . ')\b/i', '<a href="www.domain.com/$1">$1</a>', $string);
echo $string;

Output:

My content contains <a href="www.domain.com/orange">orange</a> and also blue in a blackout

Demo on 3v4l.org

Note that by using a regex with word boundaries (\b) we can avoid unintentionally replacing black in blackout with a link.

Upvotes: 3

Related Questions