简体   繁体   中英

Replace characters that are enclosed with quotes using a regular expression

How can I replace characters with preg_replace , that are enclosed in quotes?

I need to replace all special characters, that are in href="" things. Example:

<a href="ööbik">ööbik</a> should become <a href="oobik">ööbik</a>

To replace the "special chars", you need to use iconv : $str = iconv('UTF-8', 'ASCII//TRANSLIT', $str);

As for getting the values in between the quotes, see the other answers. Use preg_replace_callback to execute the conversion above on the matches.

EDIT: spoon-feeding everything together:

<?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";

This example assumes PHP 5.3. Use "create_function" or a named function if you are stuck on PHP 5.2 or below.

尽管Stack Overflow问题使用正则表达式在C#中查找带转义引号的带引号的字符串可能会帮助您找到带引号的文本,但我认为更好的解决方案是通过解析HTML字符串并使用其DOM来做到这一点。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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