php to extract a string from double quote

妖精的绣舞 提交于 2019-11-27 19:04:27

As long as the format stays the same you can do this using a regular expression. "([^"]+)" will match the pattern

  • Double-quote
  • At least one non-double-quote
  • Double-quote

The brackets around the [^"]+ means that that portion will be returned as a separate group.

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

For everyone hunting for a full featured string parser, try this:

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

Use in preg_match:

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

Returns:

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

This works with single and double quoted string fragments.

Try this :

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

You should get all your extracted strings in $results[1].

Unlike other answers, this supports escapes, e.g. "string with \" quote in it".

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

The regular expression '"([^\\"]+)"' will match anything between two double quotes.

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

Just use str_replace and escape the quote:

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

Edit:

Sorry, didnt see that there was text after the 2nd quote. In that case, I'd simply to 2 searches, one for the first quote and one for the 2nd quote, and then do a substr to extra all stuff between the two.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!