开发者

regex with special characters in php

开发者 https://www.devze.com 2022-12-26 08:25 出处:网络
I\'m trying to preg_replace charset=blablabla; and charset=blablabla\" with charset=utf-8;and charset开发者_运维问答=utf-8\". Please see ; = and \" characters, and of course searched string can be low

I'm trying to preg_replace charset=blablabla; and charset=blablabla" with charset=utf-8; and charset开发者_运维问答=utf-8". Please see ; = and " characters, and of course searched string can be lower/uppercase.

Can you help me?


You could replace the value with something like:

$subject = 'Testing... charset=baz; and charset=bat" :-)';
echo preg_replace('/(?<=charset=)[a-zA-Z0-9_-]+(?=[;"])/', 'utf-8', $subject);
// Testing... charset=utf-8; and charset=utf-8" :-)

Deconstructed, the regex matches:

  • A point immediately following charset= (using a lookbehind)
  • A sequence of one or more alphanumeric, underscore or hyphen characters (to be replaced)
  • If followed by either a semicolon or double quote character


You could try something like this.

echo preg_replace("#charset=[a-zA-Z0-9]+(\;)?#", "charset=utf-8$1", "charset=sdfsfsds");
0

精彩评论

暂无评论...
验证码 换一张
取 消