tags:

views:

37

answers:

3
+2  Q: 

PHP replace string

$string = 'http://site.com/category/1/news/2134/'; // '1' is dynamic

How can I change 1 to any number I want?

Can't call parts of the string, its just a text-like variable.

It can be done with some true regex.

+2  A: 
$array = explode('/',$string);
$array[4] = '666';
$string = implode('/',$array);

[edit] @People downvoting, what seems to be the problem with this approach?

Robus
That's pretty fragile for any string-processing task. It's not even going to break in a convincing way if the input is not well-formed.
Gian
+1  A: 

Without more information, my best guess at your problem is :

<?php
$string = 'http://site.com/category/' . $yourNumberHere . '/news/2134/';
?>
HoLyVieR
+2  A: 
$string = preg_replace('~(?<=category/)[0-9]+(?=/news)~', '56', $string);

This replaces the number by 56.

This approach uses a regex with assertions.

nikic