我正在使用google translate api来处理一些简单的东西,但是当将英语翻译成其他语言时,它有时会在引号之间给出空格,所以有人可以在php中给我一个正则表达式匹配语句来替换引号之间的空格单词和引用以及最后一个字?
示例翻译短语: 单词单词“在伦敦建构”字词单词
我希望正则表达式将其转换为: 单词单词“在伦敦建构”字词单词
谢谢!
答案 0 :(得分:1)
这是模式:"\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
这也适用于多个引用的细分:
$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
修饰符与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
已编辑以使用Phil Brown的建议。
已编辑以使用Alan Moore的建议。