0

我想要一个正则表达式,它会在双引号中的文本元素的开头和结尾删除额外的空格。目前我没有想出一个可行的方法。

例如。转换

马丁说“oogle booogle”,玛莎说“totty wottie”

马丁说“oogle booogle”,玛莎说“totty wottie”

谢谢,

标记

4

4 回答 4

5

您应该能够使用简单的正则表达式,例如/"\s*(.*?)\s*"/并替换为"$1".

正则表达式的解释:

  • "- 一个字面"人物
  • \s*- 空格/制表符/换行符重复 0 次或更多次
  • (.*?)- 一个惰性捕获组尽可能少地匹配,直到它到达下一部分:
  • \s*- 空格/制表符/换行符重复 0 次或更多次
  • "- 一个字面"人物

代码

<?php
    $string = 'Martin said " oogle booogle" and Martha said " totty wottie "';
    $string = preg_replace('/"\s*(.*?)\s*"/', '"$1"', $string);
    var_dump($string);
    //string(58) "Martin said "oogle booogle" and Martha said "totty wottie""
?>

演示

于 2013-04-08T10:40:09.943 回答
0
$string = 'Martin said " oogle booogle" and Martha said " totty wottie "';

$str = preg_replace_callback(
    '/"(.*?)"/',
    function ($matches) {
        return '"' . trim($matches[1]) . '"';
    },
    $string
);

var_dump($str);
于 2013-04-08T10:36:51.360 回答
0

试试这个

$a = 'Martin said " oogle booogle" and Martha said " totty wottie "';
function Replace1($M){
  //print_r($M);
  return "\"".trim($M[1])."\"";
}
$new=preg_replace_callback("#\"[ ]*(.*?)[ ]*\"#","Replace1",' '.$a.' ');
echo($new);

输出

Martin said "oogle booogle" and Martha said "totty wottie"
于 2013-04-08T10:42:06.270 回答
0

虽然马克贝克提供的答案会奏效,但我认为这有点过于复杂了。你不需要回调,一个简单的preg_replace就可以了:

$string = 'Martin said " oogle booogle" and Martha said " totty wottie "';
$str = preg_replace('/"\s*(.*?)\s*"/', '"$1"', $string);
于 2013-04-08T10:46:31.197 回答