PHP – Replace part of a string [closed]

Use a regular expression. str_replace will only replace static values.

$RAMBOX = 'hardwareSet[articles][123]';
$Find = '/hardwareSet\[articles\]\[\d+\]/';
$RAMBOX = preg_replace($Find, $Replace, $RAMBOX);



The /s are delimiters. The \s are escaping the []s. The \d is a number. The + says one or more numbers.

Regex101 Demo:

If you want to capture the number put the \d+ inside a capture group, (). That will be referenced as $1 in the replace value.

Browse More Popular Posts

Leave a Comment