Biker John
Biker John

Reputation: 2711

Replace specific strings in text with clickable links

For example i have some plain text.

Tintin in Tibet is the s:20 volume of The Adventures of Tintin, the comics series by Belgian cartoonist Hergé. The cartoonist considered it his favourite Tintin adventure and an emotional effort, as he created it while suffering from traumatic nightmares and a personal conflict while deciding to leave his wife of s:3 decades for a younger woman.

What i need is to convert specific custom links in text to clickable links, using number after colon. (s:number)

So the s:10 would convert to http://somepage.com/demo.php?num=10

In this case:

$text = "Tintin in Tibet is the s:20 volume of The Adventures of Tintin.";

The idea here is probably searching for specific form of string using regex and replacing it with the exploded (extracting the number) and modified (converting to link) version of itself, but i am not really good with regex and have no idea how to do this in practice.

Also, what would be the fastest option, when you have many instances of replaceable strings throughout the text?

Upvotes: 1

Views: 57

Answers (1)

rdiz
rdiz

Reputation: 6176

You are correct, the best way to get around this would be regex:

$yourText = "Tintin in Tibet.....";
$linkText = preg_replace('/s:([0-9]+)/', '<a href="http://somepage.com/demo.php?num=$1">s:$1</a>', $yourText); 
echo $linkText;

We're matching anything that says s: followed by any number ([0-9]+ means "one or more digits". You could do \d+, but [0-9]+ is more readable in my opinon). With the parenthesis, we're capturing whatever is matched between them; in this case the number. We're then injecting the first match (what was in between the first pair of parenthesis) with $1 (Which preg_replace interprets as references to matched sets) into an anchor tag.

Upvotes: 1

Related Questions