Reputation: 351
I need to use a custom PHP function to process this data,
Austin Metro>Central Austin|Austin Metro>Georgetown|Austin Metro>Lake Travis | Westlake|Austin Metro>Leander | Cedar Park|Austin Metro>Round Rock | Pflugerville | Hutto|Austin Metro>Southwest Austin
and convert it so that it reads like this:
Austin Metro>Central Austin#Austin Metro>Georgetown#Austin Metro>Lake Travis | Westlake#Austin Metro>Leander | Cedar Park#Austin Metro>Round Rock | Pflugerville | Hutto#Austin Metro>Southwest Austin
Currently using the following but is also replacing the character "|" between "Leander | Cedar Park". Is there a way to only replace the ones with no space before or after?
preg_replace("/|/", "#", {categories[1]} );
Any suggestions? Thanks!
Upvotes: 1
Views: 403
Reputation: 11942
What you're looking for is called a look ahead/behind assertion in PCRE. Specifically you want a negative look behind and negative look ahead for space surrounding your pipe. Also you should note that the character |
has special meaning in PCRE so you need to escape it to get a literal.
preg_replace('/(?<! )\|(?! )/', '#', $str);
The (?<! )
is a negative look-behind. It says match the character |
, but only if it is not proceeded by a space. The (?! )
is the negative look ahead. It says match the character |
but only if it is not followed by a space.
Upvotes: 1