我有一个字符串:

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

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

您的余额还剩 0.10 美元

我努力了 preg_match_all() 但没有运气。

有帮助吗?

解决方案

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

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

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

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

其他提示

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

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

在preg_match中使用:

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

返回:

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

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

试试这个:

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

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

与其他答案不同,它支持转义,例如&quot; string with \“引用它“

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

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

$string = '"Your Balance left <*>.10", End 0';
preg_match('"([^\\"]+)"', $string, $result);
echo $result[0];

只需使用str_replace并转义引号:

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

编辑:

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top