gogol75 gogol75 - 1 year ago 72
PHP Question

How to replace numbers in string with link containing the same number

I have a simple HTML page, containing lists of numbers. Like this:


Look at the following pages: 23, 509, 209, 11, 139, 68, 70-72, 50, 409-412


I want to replace every number, or range with a hyperlink like that:


<a href="www.mysite.com?page=23">23</a>, <a href="www.mysite.com?page=509">509</a> ..... <a href="www.mysite.com?page=409">409-412</a>



The numbers are only two and three digits and are enclosed in commas except the first and the last. And there are some ranges like 391-397

Answer Source

You can use PHP preg_replace() to achieve what you want.

$original_string = 'Look at the following pages: 23, 509, 209, 11, 139, 68, 70-72, 50, 409-412';

$updated_string = preg_replace(
   '~((\d{2,3})(\-\d{2,3})?)~', 
   '<a href="//www.mysite.com?page=$2">$1</a>', 
   $original_string
);

echo $updated_string;

See it working here.

The () sections in the first argument of preg_replace() can be referenced in the second argument with $1, $2 etc... The first enclosed section ($1) is the page number or page range ("23", "70-72"). The second enclosed section ($2) is the page number or first number of the page range.

There's plenty of resources with more info on regex online, you can play around with the regex I've written here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download