php - regex matching question
I'm using the google translate api for some simple stuff but when translating english to other languages it someti开发者_如何学Gomes 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?
Example translated phrase: word word word " constructie in Londen " word word word
I would like the regex to convert it to: word word word "constructie in Londen" word word word
Thanks!
This is the pattern: "\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:
$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.
精彩评论