在捕获组中寻找特定字符
Looking for specific character in capture group
我需要替换任何(变量)给定字符串中的所有双引号。
例如:
$text = 'data-caption="hello"world">';
$pattern = '/data-caption="[[\s\S]*?"|(")]*?">/';
$output = preg_replace($pattern, '"', $text);
应该导致:
"hello"world"
(上面的模式是我尝试让它工作的)
问题是我现在不知道字符串中是否以及有多少个双引号。
如何将 "
替换为 quot;
?
您可以匹配 data-caption="
和 ">
之间的字符串,然后仅使用 str_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_replace_callback
中的匿名函数(可通过 $m[0]
访问),这就是可以方便地替换所有 "
符号的地方。
我需要替换任何(变量)给定字符串中的所有双引号。
例如:
$text = 'data-caption="hello"world">';
$pattern = '/data-caption="[[\s\S]*?"|(")]*?">/';
$output = preg_replace($pattern, '"', $text);
应该导致:
"hello"world"
(上面的模式是我尝试让它工作的)
问题是我现在不知道字符串中是否以及有多少个双引号。
如何将 "
替换为 quot;
?
您可以匹配 data-caption="
和 ">
之间的字符串,然后仅使用 str_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_replace_callback
中的匿名函数(可通过 $m[0]
访问),这就是可以方便地替换所有 "
符号的地方。