php-regex匹配问题
我正在使用google translate api来处理一些简单的东西,但是当将英语翻译成其他语言时,它有时会在引号之间留出空格,所以有人能给我一个php中的正则表达式匹配语句来替换引号和第一个单词之间以及引号和最后一个单词之间的空格吗 翻译短语示例: 单词“伦敦的建筑”单词 我希望正则表达式将其转换为: 单词“伦敦的建筑”单词php-regex匹配问题,php,regex,Php,Regex,我正在使用google translate api来处理一些简单的东西,但是当将英语翻译成其他语言时,它有时会在引号之间留出空格,所以有人能给我一个php中的正则表达式匹配语句来替换引号和第一个单词之间以及引号和最后一个单词之间的空格吗 翻译短语示例: 单词“伦敦的建筑”单词 我希望正则表达式将其转换为: 单词“伦敦的建筑”单词 谢谢 这是模式:“\s*(.*?\s*” 这也适用于多个引用段: $str = 'word word word " constructie in Londen " wo
谢谢 这是模式:
“\s*(.*?\s*”
这也适用于多个引用段:
$str = 'word word word " constructie in Londen " word word wordword word word " constructie in Londen " word word wordword word word " constructie in Londen " word word word';
$newStr = preg_replace('/"\s*(.*?)\s*"/', '"\\1"', $str);
echo $newStr;
// word word word "constructie in Londen" word word wordword word word "constructie in Londen" word word wordword word word "constructie in Londen" word word word
或者您可以使用带有修剪的/e
修改器:
$str = 'word word word " constructie in Londen " word word wordword word word " constructie in Londen " word word wordword word word " constructie in Londen " word word word';
$newStr = preg_replace('/"(.*?)"/e', "'\"'.trim('\\1').'\"'", $str);
echo $newStr;
// word word word "constructie in Londen" word word wordword word word "constructie in Londen" word word wordword word word "constructie in Londen" word word word
编辑以使用菲尔·布朗的建议
编辑以使用艾伦·摩尔的建议。是否保证不会有不匹配的引号?不确定您的意思,有些短语可能有引号,有些短语可能没有。因此,如果没有匹配的引号,那么显然正则表达式不会对字符串做任何处理。Ie在整个文本字符串中有奇数个引号而不是偶数。您也可以使用非贪婪匹配,而不是“除引号外的所有内容”范围,例如
/“\s”(.*?)\s?”/
@Phil,我不确定为什么这样做有效,但它确实有效,而且更干净。好极了。我得用谷歌搜索一下,替换中的trim()调用不需要显式匹配空格'/“(.*?)/e'
和'/“([^”]*)”/e'
一样有效。或者您可以放弃trim(),充分利用不情愿的量词:$newStr=preg_replace('/“\s*([^”]*?)\s*“/”、“$1”、$str)代码>-ref:@Alan:你说得对。这场比赛最初是不同的,它确实需要\s?
s,但由于菲尔·布朗的评论,它被更新了。现在它可以简化很多。我将再次更新它以反映您的输入。
$str = 'word word word " constructie in Londen " word word wordword word word " constructie in Londen " word word wordword word word " constructie in Londen " word word word';
$newStr = preg_replace('/"(.*?)"/e', "'\"'.trim('\\1').'\"'", $str);
echo $newStr;
// word word word "constructie in Londen" word word wordword word word "constructie in Londen" word word wordword word word "constructie in Londen" word word word