[Solved] 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+\]/';
$Replace="hardwareSetRAM";
$RAMBOX = preg_replace($Find, $Replace, $RAMBOX);

Output:

hardwareSetRAM

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

Regex101 Demo: https://regex101.com/r/jS6nO9/1

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

1

solved PHP – Replace part of a string [closed]