Jump to content

Replace a number in a string for another number


papaface

Recommended Posts

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 :)

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

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!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.