Php replace string

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

How do I change 1to any number I want?

It is not possible to call parts of a string, its just a text variable.

This can be done with some true regex.

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

This replaces the number with 56.

This approach uses a regex with assertions .

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

[edit] @Power downvoting, what seems to be a problem with this approach?

+2
source

Without further information, my best guess about your problem:

<?php
$string = 'http://site.com/category/' . $yourNumberHere . '/news/2134/';
?>
+2
source

Source: https://habr.com/ru/post/1763079/


All Articles