【问题标题】:How to extract a string from double quotes?如何从双引号中提取字符串?
【发布时间】:2009-06-19 09:17:06
【问题描述】:

我有一个字符串:

这是一个文本,“您的余额还剩 0.10 美元”,结束 0

如何提取双引号之间的字符串并且只有文本(没有双引号):

您的余额还剩 0.10 美元

我尝试了preg_match_all(),但没有成功。

【问题讨论】:

标签: php string preg-match preg-match-all double-quotes


【解决方案1】:

只要格式保持不变,您就可以使用正则表达式来执行此操作。 "([^"]+)" 将匹配模式

  • 双引号
  • 至少一个非双引号
  • 双引号

[^"]+ 周围的括号表示该部分将作为单独的组返回。

<?php

$str  = 'This is a text, "Your Balance left $0.10", End 0';

//forward slashes are the start and end delimeters
//third parameter is the array we want to fill with matches
if (preg_match('/"([^"]+)"/', $str, $m)) {
    print $m[1];   
} else {
   //preg_match returns the number of matches found, 
   //so if here didn't match pattern
}

//output: Your Balance left $0.10

【讨论】:

    【解决方案2】:

    对于所有寻找功能齐全的字符串解析器的人来说,试试这个:

    (?:(?:"(?:\\"|[^"])+")|(?:'(?:\\'|[^'])+'));
    

    在 preg_match 中使用:

    $haystack = "something else before 'Lars\' Teststring in quotes' something else after";
    preg_match("/(?:(?:\"(?:\\\\\"|[^\"])+\")|(?:'(?:\\\'|[^'])+'))/is",$haystack,$match);
    

    返回:

    Array
    (
        [0] => 'Lars\' Teststring in quotes'
    )
    

    这适用于单引号和双引号字符串片段。

    【讨论】:

    • 有效,但有没有办法从返回的字符串中排除引号本身?
    【解决方案3】:

    试试这个:

    preg_match_all('`"([^"]*)"`', $string, $results);
    

    您应该在 $results[1] 中获取所有提取的字符串。

    【讨论】:

      【解决方案4】:

      与其他答案不同,这支持转义,例如"string with \" quote in it".

      $content = stripslashes(preg_match('/"((?:[^"]|\\\\.)*)"/'));
      

      【讨论】:

        【解决方案5】:

        正则表达式'"([^\\"]+)"' 将匹配两个双引号之间的任何内容。

        $string = '"Your Balance left $0.10", End 0';
        preg_match('"([^\\"]+)"', $string, $result);
        echo $result[0];
        

        【讨论】:

        • 双引号被用作此 sn-p 中的模式分隔符。不要在你的项目中使用这个 sn-p。
        【解决方案6】:

        只需使用 str_replace 并转义引号:

        str_replace("\"","",$yourString);
        

        编辑:

        抱歉,没有看到第二个引用之后有文字。在这种情况下,我只需进行 2 次搜索,一个用于第一个引号,一个用于第二个引号,然后执行 substr 以在两者之间添加所有内容。

        【讨论】:

        • 它不是一个有效的正则表达式!
        猜你喜欢
        • 1970-01-01
        • 2012-07-07
        • 2021-12-19
        • 1970-01-01
        • 1970-01-01
        • 2013-11-09
        • 1970-01-01
        • 2021-11-16
        相关资源
        最近更新 更多