Page 1 of 1
I need simple help on Regex
Posted: Sun Jul 04, 2010 1:40 pm
by soul|fly
I know regex basics well. But I couldn't figure out following problem while I doing my mini project. Let me explain you a bit:
The following is given in normal html file:
{
"Subject": "English 101",
"name": "Dave More",
"Grade": "A-",
}
What I was asked to do is that to grab name info and to echo it by php.
what I tried is that
preg_match_all('/name\W\W\s\W([^"]+)\W/', $school, $name); // $school is where the html is stored
echo $name;
I just wanted the output to be:
Dave More
but it give me out Array.
Would you mind to co-operate? plz
thanks
Re: I need simple help on Regex
Posted: Tue Jul 06, 2010 1:00 pm
by soul|fly
poking around for 2/3 days for an answer. Anyone?
Re: I need simple help on Regex
Posted: Tue Jul 06, 2010 1:39 pm
by AbraCadaver
Look at the manual for preg_match_all(). What is populated in the $school variable? Also, you probably only need preg_match() unless you have multiple names.
Re: I need simple help on Regex
Posted: Tue Jul 06, 2010 11:51 pm
by soul|fly
$School is populated with following:
{
"Subject": "English 101",
"name": "Dave More",
"Grade": "A-",
}
Please be specific in answer. I just told what I tried and actually tried bunch of preg_match combination. No luck yet. I know i'm lacking somewhere.
Re: I need simple help on Regex
Posted: Wed Jul 07, 2010 9:02 am
by AbraCadaver
My bad. What I meant is what is stored in $name. The manual tells you and you can use print_r() or var_dump() to find out as well.
Re: I need simple help on Regex
Posted: Wed Jul 07, 2010 6:03 pm
by soul|fly
If I do print_r($name) it gives output like:
Array ( [0] => Array ( ) [1] => Array ( ) )
And if I do var_dump($name) it gives output like:
array(2) { [0]=> array(0) { } [1]=> array(0) { } }
Btb, when I do the echo $school; it shows as follows: (for your reference)
{"Subject":"English 101","name":"Dave More","Grade":"A"}
May be I'm doing something wrong with regex. You you plz look at it?
Re: I need simple help on Regex
Posted: Wed Jul 07, 2010 6:10 pm
by AbraCadaver
Code: Select all
preg_match('/"name": "([^"]+)"/', $school, $name);
print_r($name);
But since that looks like a json encoded string, this makes more sense:
Code: Select all
$object = json_decode($school);
echo $object->name;
Re: I need simple help on Regex
Posted: Wed Jul 07, 2010 11:53 pm
by soul|fly
Thanks for your support. I guess I solved the problem.