php从双引号中提取字符串

con*_*dor 25 php string preg-match-all preg-match double-quotes

我有一个字符串:

这是一个文字,"你的余额留下0.10美元",结束0

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

你的余额剩下0.10美元

我试过preg_match_all()但没有运气.

Tom*_*igh 57

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

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

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

<?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
Run Code Online (Sandbox Code Playgroud)


小智 16

对于每个人都在寻找一个功能齐全的字符串解析器,试试这个:

(?:(?:"(?:\\"|[^"])+")|(?:'(?:\\'|[^'])+'));
Run Code Online (Sandbox Code Playgroud)

在preg_match中使用:

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

返回:

Array
(
    [0] => 'Lars\' Teststring in quotes'
)
Run Code Online (Sandbox Code Playgroud)

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

  • 但是有没有办法从返回的字符串中排除引号本身? (3认同)

小智 9

试试这个 :

preg_match_all('`"([^"]*)"`', $string, $results);
Run Code Online (Sandbox Code Playgroud)

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


Kor*_*nel 5

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

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