5

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?

0

4 Answers 4

10

http://www.php.net/preg_match

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

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

print_r($matches);

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

*/
?>
3
  • The same that I had come up with. :-) Sep 2, 2009 at 2:55
  • 2
    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
    Sep 3, 2009 at 4:40
  • 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
    Sep 6, 2009 at 16:42
1
<?php

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

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

var_dump($matches);
1
$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).

1

$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
1
  • @opello, @Patrick - could anyone of you please explain this answer a little bit... I am still new to regex. I want to do a similar task - "read the number right after site_ids== from site_ids==34||sales_region==45" (i.e. regex should return 34). I tried with preg_match('/^[^site_ids==]*||([^||]*)"$/', $str, $matches); after $str = 'site_ids==34||sales_region==45'; and not getting result. I am not sure if | needs escaping. The delimiter in the question is a double quote (") whereas in my case they are site_ids== and ||. What would be correct regex for me? Thanks. Jun 20, 2011 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.