使用 PHP 函数将一个字符替换为另一个字符

Replace one character with another using PHP function

我需要使用自定义 PHP 函数来处理这些数据,

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

并将其转换为如下所示:

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

目前正在使用以下字符但也在替换字符“|” "Leander | Cedar Park" 之间。有没有办法只替换之前或之后没有 space 的?

 preg_replace("/|/", "#", {categories[1]} );

有什么建议吗?谢谢!

您要找的是外观 ahead/behind assertion in PCRE。具体来说,您希望对管道周围的 space 进行消极的回顾和消极的展望。您还应该注意字符 | 在 PCRE 中具有特殊含义,因此您 需要 对其进行转义以获得文字。

preg_replace('/(?<! )\|(?! )/', '#', $str);

(?<! ) 是消极的回顾。它表示匹配字符 |,但前提是它前面没有 space。 (?! ) 是消极的展望。它说匹配字符 | 但前提是它后面没有跟 space.