Why won't this ampersand matching regexp work?
I need to use this PHP snippet to convert & to ampersand. I am using the exact same test code as Paul Dixon has written it, but no ampersands are replaced in my code. Why? I am using PHP 5.2.6.
$str_fix = preg_replace('/&(?!#?[a-z0-9]+;)/', '&', $str);
The following, simpler but incorrect (it will also replace开发者_JS百科 the & in &) regexp works:
$str_fix = preg_replace('/&/', '&', $str);
EDIT: Damnit, the issue isn't regexp/PHP related but Drupal! Yes, I am using this snippet in a Drupal module and for some reason Drupal converts & to &.
If Drupal is replacing & with & you can just double escape the entity:
$str_fix = preg_replace('/&(?!#?[a-z0-9]+;)/', '&', $str);
Then Drupal will output & which was your desired result.
What about using str_replace('&', '& ;', $str)?
Could you give us an example input string?
echo preg_replace('/&(?!#?[a-z0-9]+;)/', '&', "Dogs & Cats & budgies\n");
correctly produces
Dogs & Cats & budgies
加载中,请稍侯......
精彩评论