PHP - Replace partially matching string.
Posted July 29th 2014, 11:46pm
I need to use PHP to replace a part of string, but there is a section of that string that will always be a different value. I need that value to stay a part of what the string is replaced with. How can I do this?

Since what I wrote may be kind of confusing to follow, let me give an example. Say I have a string that at various points, has the text blargh="5" reoccurring throughout it with different numbers each time. Every time blargh="9" or blargh="3" appears, I want to replace the text with potato chips=#4# while still maintaining the number, so blargh="4" would convert to potato chips=#4# and blargh="97" would convert to potato chips=#97#.
φ
Posts: 280
Joined: October 2nd 2011, 11:00pm
Likes Given: 27
Likes Received: 4
PHP - Replace partially matching string.
Posted July 30th 2014, 9:06am
You can use the preg_replace() function:

$string = preg_replace('!blargh="(\d+)"!', 'potato chips=#$1#', $string);

where $string is the string you want to check. The important part is the (\d+) parameter. That tells preg_replace() to match 1 or more numbers, and remember the match as $1.
φ
Posts: 1599
Joined: March 12th 2009, 11:00pm
Location: Uncertain due to momentum
Likes Given: 26
Likes Received: 357
PHP - Replace partially matching string.
Posted July 30th 2014, 8:13pm
preg_replace() is so confusing! It seems that whenever I try to add braces at the beginning and end of the thing I want to replace, I get this:

[blargh="4"] // Before...
// ...and After
[potato chips=##potato chips=##potato chips=##potato chips=##potato chips=##potato chips=##potato chips=##potato chips=##potato chips=##potato chips=##]
φ
Posts: 280
Joined: October 2nd 2011, 11:00pm
Likes Given: 27
Likes Received: 4
PHP - Replace partially matching string.
Posted July 30th 2014, 10:46pm
Braces are special characters in regular expressions, so they must be escaped with backslashes if you want to test for them. For example:

$string = preg_replace('!\[blargh="(\d+)"\]!', '[potato chips=#$1#]', $string);
φ
Posts: 1599
Joined: March 12th 2009, 11:00pm
Location: Uncertain due to momentum
Likes Given: 26
Likes Received: 357
PHP - Replace partially matching string.
Posted July 31st 2014, 7:13pm
Okay thank you. I was not aware of this.
φ
Posts: 280
Joined: October 2nd 2011, 11:00pm
Likes Given: 27
Likes Received: 4

Who is online

Users browsing this forum: No registered users and 0 guests