Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a string from double quotes?

I have a string:

This is a text, "Your Balance left $0.10", End 0

How can I extract the string in between the double quotes and have only the text (without the double quotes):

Your Balance left $0.10

I have tried preg_match_all() but with no luck.

like image 736
conandor Avatar asked Jun 19 '09 09:06

conandor


People also ask

How do you escape quotation marks in a string?

You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.

How do I convert a string between two quotes in Excel?

You can also insert a double quote in an Excel formula using the CHAR function. The CHAR function takes the ASCII value and returns the corresponding character value. The ASCII value for a double quote is 34.


2 Answers

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 
like image 129
Tom Haigh Avatar answered Sep 22 '22 02:09

Tom Haigh


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.

like image 22
user426486 Avatar answered Sep 19 '22 02:09

user426486