papaface Posted November 28, 2010 Share Posted November 28, 2010 Hey I have a string that looks like the following: top-php-tutorials-2.html I have a script that cycles through each page. The 2 in the quote above is the page number. How can I extract the number between the - and the .html and replace it with another number? I've tried substr($engine->selectedcaturl, 0,-6).$v.".html" But then I realised this only works for numbers that are 1 digit long Any input would be appreciated Link to comment https://forums.phpfreaks.com/topic/220075-replace-a-number-in-a-string-for-another-number/ Share on other sites More sharing options...
kenrbnsn Posted November 28, 2010 Share Posted November 28, 2010 You can use preg_replace. Here's and example: <?php $fn = 'top-php-tutorials-2.html'; $pat = '/(\w+)-(\w+)-(\w+)-(\d+).(\w+)/i'; $v = '100'; $repl = '$1-$2-$3-' . $v . '.$4'; $nfn = preg_replace($pat,$repl,$fn); echo $nfn; ?> Ken Link to comment https://forums.phpfreaks.com/topic/220075-replace-a-number-in-a-string-for-another-number/#findComment-1140636 Share on other sites More sharing options...
papaface Posted November 28, 2010 Author Share Posted November 28, 2010 You can use preg_replace. Here's and example: <?php $fn = 'top-php-tutorials-2.html'; $pat = '/(\w+)-(\w+)-(\w+)-(\d+).(\w+)/i'; $v = '100'; $repl = '$1-$2-$3-' . $v . '.$4'; $nfn = preg_replace($pat,$repl,$fn); echo $nfn; ?> Ken Thanks for that Ken! Works perfectly. I really need to learn me some regex! Link to comment https://forums.phpfreaks.com/topic/220075-replace-a-number-in-a-string-for-another-number/#findComment-1140638 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.