如何用preg_replace
替换用引号括起来的字符?
我需要替换href=""
内容中的所有特殊字符。例如:
<a href="ööbik">ööbik</a> should become <a href="oobik">ööbik</a>
答案 0 :(得分:4)
要替换“特殊字符”,您需要使用iconv:$str = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
至于获取引号之间的值,请参阅其他答案。使用preg_replace_callback
在匹配项上执行上述转换。
<?php
$input = 'ööbik';
$expected = 'ööbik';
// Set the locale of your input here.
setlocale(LC_ALL, 'en_US');
// Convert using a callback.
$output = preg_replace_callback('/href="([^"]+)"/', function ($matches) {
return iconv('UTF-8', 'ASCII//TRANSLIT', $matches[0]);
}, $input);
echo "Input: $input\n";
echo "Expected: $expected\n";
echo "Output: $output\n";
此示例假定为PHP 5.3。如果您遇到PHP 5.2或更低版本,请使用“create_function”或命名函数。
答案 1 :(得分:0)
虽然Stack Overflow问题 Finding quoted strings with escaped quotes in C# using a regular expression 可以帮助您查找引用文本,但我认为更好的解决方案是通过解析HTML字符串并使用其DOM来完成此操作