用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
中的撇号很简单。模式为/(w+)'(w+)/
的preq_replace
将在单词中找到撇号。但是我不能很好地调换演讲词的引语。当前我有:
$singlequotesPattern = "/'(.*)'/";
$singlequotesReplacement = "‘$1’";
$singlequotes = preg_replace($singlequotesPattern, $singlequotesReplacement, $text);
但是上面的语句失败了,并产生Jane said ‘How do we do this?' 'I don't know’ replied Sam.
它只匹配最外面的单引号。如何使其替换这两对引号?
解决方案
$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.
^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^
相关文章