tags:

views:

72

answers:

4

I have a text title that reads

This User "The Title Of The Post"

I want to grab just whats INSIDE of the quotation marks, and store it in a variable. How would i do this with regex and php?

+4  A: 

http://www.php.net/preg%5Fmatch

<?php
$x = 'This User "The Title Of The Post"';

preg_match('/".*?"/', $x, $matches);

print_r($matches);

/*
  Output:
  Array
  (
      [0] => "The Title Of The Post"
  )

*/
?>
opello
The same that I had come up with. :-)
Alan Haggai Alavi
not global :,-(
jakemcgraw
The poster asked for "just whats INSIDE of the quotation marks" and the accepted solution includes quotation marks. My solution excludes quotation marks as the poster requested.
Asaph
So either the question or the answer should change for archival purposes. Changing the pattern to /"(.*?)"/ has the desired output in $matches[1]. Changing the function call to use preg_match_all (per jakemcgraw) would hold the desired output in $matches[1][0] (and subsequent unquoted matches in $matches[1][1..n]).
opello
A: 
<?php

$string = 'This User "The Title Of The Post"';

preg_match_all('/"([^"]+)"/', $string, $matches);

var_dump($matches);
jakemcgraw
A: 
$string = 'This user "The Title Of The Post"';

$its_a_match = preg_match('/"(.+?)"/', $string, $matches);
$whats_inside_the_quotes = $matches[1];

$its_a_match will be 1 if it made a successful match, otherwise 0. $whats_inside_the_quotes will contain the string matched in the set of parentheses in the regex.

In case it's a bit unclear (it is), preg_match() actually gives a value to $matches (the third argument).

yjerem
+1  A: 

$str = 'This User "The Title Of The Post"';
$matches = array();
preg_match('/^[^"]*"([^"]*)"$/', $str, $matches);
$title = $matches[1];
echo $title; // prints The Title Of The Post
Asaph