Php 在捕获组中查找特定角色

Php 在捕获组中查找特定角色,php,preg-replace,pcre,Php,Preg Replace,Pcre,我需要替换任何(变量)给定字符串中的所有双引号 例如: $text = 'data-caption="hello"world">'; $pattern = '/data-caption="[[\s\S]*?"|(")]*?">/'; $output = preg_replace($pattern, '"', $text); 应导致: "hello"world" (以上模式是我试图让它发挥作用的尝试) 问题是,我现在不知道字符串中是否有双引号,

我需要替换任何(变量)给定字符串中的所有双引号

例如:

$text = 'data-caption="hello"world">';
$pattern = '/data-caption="[[\s\S]*?"|(")]*?">/';
$output = preg_replace($pattern, '"', $text);
应导致:

"hello"world" 
(以上模式是我试图让它发挥作用的尝试)

问题是,我现在不知道字符串中是否有双引号,以及有多少双引号


如何将
替换为

您可以在
数据标题=“
”>
之间匹配字符串,然后仅使用
str\u replace
替换与
匹配的所有

$text = 'data-caption="<element attribute1="wert" attribute2="wert">Name</element>">';
$pattern = '/data-caption="\K.*?(?=">)/';
$output = preg_replace_callback($pattern, function($m) {
        return str_replace('"', '"', $m[0]);
    }, $text);
print_r($output);
// => data-caption="<element attribute1="wert" attribute2="wert">Name</element>">

详细信息

  • data caption=“
    -起始分隔符
  • \K
    -匹配重置运算符
  • *?
    -除换行符以外的任何0+字符,尽可能少
  • (?=“>)
    -正向前瞻,需要当前位置右侧的
    “>
    子字符串

匹配被传递到
preg\u replace\u回调
(可通过
$m[0]
访问)中的匿名函数,在那里可以替换所有
以一种方便的方式匹配符号。

您想只匹配一个非常特定的字符串,还是它是较长HTML的一部分,并且该属性可以在其他属性之前/之后?这只是一个较大HTML结构的摘录。
data caption=“
”>
限制器可以多次出现。试试看,这看起来是个不错的开始,但对我来说还不起作用。也许是因为不同的弦乐组合?下面是我的文件中的一个“真实”字符串:
data caption=“element attribute1=”wert“attribute2=”wert“Name/element”>
那么,如何描述尾随分隔符呢
data caption=“
是最前面的一个。你怎么知道停在哪里?