Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace directory in the middle of a filepath string

$string = 'http://example.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.

like image 926
James Avatar asked Jan 28 '26 13:01

James


2 Answers

$string = preg_replace('~(?<=category/)[0-9]+(?=/news)~', '56', $string);

This replaces the number by 56.

This approach uses a regex with assertions.

like image 64
NikiC Avatar answered Jan 30 '26 03:01

NikiC


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

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

like image 43
Robus Avatar answered Jan 30 '26 03:01

Robus