php从双引号中提取字符串

时间:2009-06-19 09:17:06

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

我有一个字符串:

  

这是一个文字,“你的余额剩下$ 0.10”,结束0

如何在双引号之间提取字符串并且只包含文本(不带双引号):

  

您的余额剩余0.10美元

我试过preg_match_all(),但没有运气。

6 个答案:

答案 0 :(得分:55)

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

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

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

<?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

答案 1 :(得分:16)

对于寻找全功能字符串解析器的每个人,请尝试以下方法:

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

在preg_match中使用:

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

返回:

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

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

答案 2 :(得分:9)

试试这个:

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

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

答案 3 :(得分:5)

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

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

答案 4 :(得分:-1)

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

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

答案 5 :(得分:-7)

只需使用str_replace并转义引号:

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

编辑:

对不起,没看到第二次引用后有文字。在这种情况下,我只需要进行2次搜索,一次是第一次引用,另一次是第二次引用,然后在两者之间做一个额外的所有内容。

相关问题