cbielich
asked on
preg_replace example
Lets say I have a variable with
$this = '/field1/12345678/field1'
how do I write it so that I can replace 12345678 with something else
field1 and field2 may always be something different
$this = '/field1/12345678/field1'
how do I write it so that I can replace 12345678 with something else
field1 and field2 may always be something different
Tested and working:
$text = '/field1/12345678/field1';
$result = preg_replace("#^(/[^/]*/)[ ^/]*#","$1 new value",$text);
print "Result: $result\n";
Output:
Result: /field1/new value/field1
I forgot the semi-colon on the first line, and "$this" can't be used as it's a reserved variable name.
$text = '/field1/12345678/field1';
$result = preg_replace("#^(/[^/]*/)[
print "Result: $result\n";
Output:
Result: /field1/new value/field1
I forgot the semi-colon on the first line, and "$this" can't be used as it's a reserved variable name.
Explanation: This part of the pattern:
^(/[^/]*/)
captures /field1/ and is used in the replacement as $1
Just change "new value" to the value you want to use instead of 12345678
^(/[^/]*/)
captures /field1/ and is used in the replacement as $1
Just change "new value" to the value you want to use instead of 12345678
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Much faster way to do it thanks
$this = '/field1/12345678/field1'
$result = preg_replace("#^(/[^/]*/)[