Here is my code!
$Find = array('hardwareSet[articles][(.*)]');
$Replace = array('hardwareSetRAM');
$RAMBOX = str_replace($Find, $Replace, $RAMBOX);
The whole text is like this: hardwareSet[articles][RANDOMnumberHERE]
The second []
always has different numbers. I want hardwareSet[articles][WhatEverNumberIsHere]
to be changed to a string looking like hardwareSetRAM
.
How can I do that, can you help me out?
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.
Since you are using RegExp, use preg_replace
preg_replace('/hardwareSet\[articles\]\[.*\]/', 'hardwareSet[articles][hardwareSetRAM]', $string);
Your question is strange.
If you know start of the string, you can only generate new string:
$str = 'hardwareSet[articles][' . $newValue . ']';
But if you don't know any of the part in string, you can use this code:
<?php
$Find = array('hardwareSet[articles][(.*)]');
$Replace = 'hardwareSetRAM';
$RAMBOX = preg_replace('~^(.+)\[(.+)\]\[(.+)\]$~', '$1[$2][' . $Replace . ']', $Find);
var_dump($RAMBOX);
In this code doesn't meter any of parts in the string
try this
$t ='hardwareSet[articles][RANDOMnumberHERE]';
echo replace_between($t, 'hardwareSet[articles][', ']', 'hardwareSetRAM');
function replace_between($str, $needle_start, $needle_end, $replacement) {
$pos = strpos($str, $needle_start);
$start = $pos === false ? 0 : $pos + strlen($needle_start);
$pos = strpos($str, $needle_end, $start);
$end = $pos === false ? strlen($str) : $pos;
return substr_replace($str, $replacement, $start, $end - $start);
}