-2

I am a complete noob here. I am trying to extract Marine Corp. (without quotes from $data. I've searched and searched for how to deal with double quotes but am coming up short. Can someone please offer some guidance? Thank you.

$data = '"title":{"rendered":"Marine Corp."}';
preg_match('/title":{"rendered":"(.*)"}/U',$data,$matches);
echo $matches[0]; //=> target
MAB
  • 61
  • 7
  • 1
    Is that the complete data you're dealing with? Or do you possible actually have a nice [***JSON object***](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php)? – deceze Mar 16 '18 at 16:14

3 Answers3

0

The regex you're after is /\"title\"\:\{\"rendered\"\:\"(.*)\"\}/

$data = '"title":{"rendered":"Marine Corp."}';
preg_match('/\"title\"\:\{\"rendered\"\:\"(.*)\"\}/',$data,$matches);
$tmp = array_shift( $matches );

$tmp will hold "Marine Corp."

On another note it seems like you have a JSON object there. If that's the case you could do, which would be a lot simpler:

$data = '{"title":{"rendered":"Marine Corp."}}';
$tmp = json_decode($data, true);
var_dump($tmp['title']['rendered']);
Kasia Gogolek
  • 3,374
  • 4
  • 33
  • 50
0

Try like this,

<?php
//If it is valid json then try with json_decode()
$json_string = '{"title":{"rendered":"Marine Corp."}}';
$json_array = json_decode($json_string,1);
echo "For Json Object:\n" . $json_array['title']['rendered']."\n";

//If it is just string pattern then with preg_match()
$re = '/"title":{"rendered":"(.*?)\.?"}/';
$str = '"title":{"rendered":"Marine Corp."}
"title":{"rendered":"Marine Police"}';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
echo "\nFor String: \n";
foreach($matches as $match){
    echo $match[1]."\n";
}
?>

Output:

For Json Object:
Marine Corp.

For String: 
Marine Corp
Marine Police

See PHP demo : https://eval.in/973297

See REGEX demo : https://regex101.com/r/GyGN9U/1

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • The example $data I was showing was part of a much larger string which was not well formed json. – MAB Mar 16 '18 at 17:12
-1

if you won't to extract "Marine Corp" from the $data string use the str_replace() function:

echo str_replace('Marine Corp.', '', $data);

result: "title":{"rendered":""}