用preg_replace替换智能引号的哑引号

时间:2013-06-16 16:03:10

标签: php preg-replace

我正试图将哑巴引号换成智能等价物。因此,我想将Jane said 'How do we do this?' 'I don't know' replied Sam.转换为Jane said ‘How do we do this?’ ‘I don’t know’ replied Sam.,例如。

don't中的撇号很容易。模式为preq_replace的{​​{1}}会在单词中找到撇号。但我无法正确交换语音报价。目前我有:

/(\w+)'(\w+)/

但是这会因上面的句子失败而产生$singlequotesPattern = "/'(.*)'/"; $singlequotesReplacement = "‘$1’"; $singlequotes = preg_replace($singlequotesPattern, $singlequotesReplacement, $text); 它只匹配最外面的单引号。如何让它替换两对引号?

1 个答案:

答案 0 :(得分:1)

$singlequotesPattern = "/'(.*?)'/";

添加?以使*量词非贪婪。贪婪的量词可以找到最长的匹配。非贪婪的人发现最短的。

贪婪:

Jane said 'How do we do this?' 'I don’t know' replied Sam.
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

非贪婪:

Jane said 'How do we do this?' 'I don’t know' replied Sam.
           ^^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^