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


i have simple html page, containing lists of numbers. this:

look @ following pages: 23, 509, 209, 11, 139, 68, 70-72, 50, 409-412

i want replace every number, or range hyperlink 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 2 , 3 digits , enclosed in commas except first , last. , there ranges 391-397

you can use php preg_replace() achieve want.

$original_string = 'look @ 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 working here.

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

there's plenty of resources more info on regex online, can play around regex i've written here.


Comments

Popular posts from this blog

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

jsf - "PropertyNotWritableException: Illegal Syntax for Set Operation" error when setting value in bean -

laravel - Undefined property: Illuminate\Pagination\LengthAwarePaginator::$id (View: F:\project\resources\views\admin\carousels\index.blade.php) -