Link to home
Start Free TrialLog in
Avatar of cbielich
cbielichFlag for United States of America

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
Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

This should do it:

$this = '/field1/12345678/field1'
$result = preg_replace("#^(/[^/]*/)[^/]*#","$1new value",$this);
Tested and working:

$text = '/field1/12345678/field1';
$result = preg_replace("#^(/[^/]*/)[^/]*#","$1new 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.
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
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of cbielich

ASKER

Much faster way to do it thanks