简体   繁体   English

php-正则表达式匹配问题

[英]php - regex matching question

I'm using the google translate api for some simple stuff but when translating english to other languages it sometimes gives me spaces between quotes, so can someone give me a regex matching statement in php to replace the space between the quote and first word and the quote and last word? 我正在使用google translation api进行一些简单的操作,但是当将英语翻译成其他语言时,有时会在引号之间给我空格,因此有人可以在php中给我一个正则表达式匹配语句来替换引号和第一个单词之间的空格以及报价和最后一句话?

Example translated phrase: word word word " constructie in Londen " word word word 例句翻译词组:单词单词单词“ Londen中的constructie”单词单词单词

I would like the regex to convert it to: word word word "constructie in Londen" word word word 我希望正则表达式将其转换为:word word word“在Londen中构建” word word word

Thanks! 谢谢!

This is the pattern: "\\s*(.*?)\\s*" 这是模式: "\\s*(.*?)\\s*"

$str = 'word 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 word

This will also work with multiple quoted segments: 这也适用于多个引用段:

$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

Or you could use the /e modifier with trim: 或者,您可以将/e修饰符与trim一起使用:

$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

Edited to use Phil Brown's suggestion. 编辑使用菲尔·布朗的建议。

Edited to use Alan Moore's suggestion. 编辑使用艾伦·摩尔的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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