简体   繁体   English

带有php中特殊字符的正则表达式

[英]regex with special characters in php

I'm trying to preg_replace charset=blablabla; 我正在尝试preg_replace charset=blablabla; and charset=blablabla" with charset=utf-8; and charset=utf-8" . charset=blablabla"charset=utf-8;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 ) charset=紧跟的点(使用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 如果后跟分号或双引号字符

您可以尝试这样的事情。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM