Expression problem

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
itsmani1
Forum Regular
Posts: 791
Joined: Mon Sep 29, 2003 2:26 am
Location: Islamabad Pakistan
Contact:

Expression problem

Post by itsmani1 »

Hi

I want to fetch 26 out of this using express. I used following code but failed.

Code: Select all

$data = '<span style="text-transform: capitalize;">cloudy</span> 26<abbr title="Temperature in degrees Celsius">°C</abbr>';    
$pattern = '/</span> (.*)<abbr title/msU';
preg_match_all($pattern, $data, $matche1);
thanks
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Re: Expression problem

Post by Oren »

You failed? of course... you have a syntax error. Don't you see it?
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Expression problem

Post by prometheuzz »

Since you already used a '/' in your regex, you must can't use '/ ... /' to denote your regex (or escape the '/' but IMO, that looks messy). Also, it;''s safer to use [^<]+ instead of .*.
Here's a way:

Code: Select all

<?php
$data = '<span style="text-transform: capitalize;">cloudy</span> 26<abbr title="Temperature in degrees Celsius">°C</abbr>';    
$pattern = '#</span>\s*+([^<]++)<abbr\s++title#msU';
if(preg_match($pattern, $data, $matches)) {
  echo $matches[1];
}
?>
devendra-m
Forum Contributor
Posts: 111
Joined: Wed Sep 12, 2007 3:16 am

Re: Expression problem

Post by devendra-m »

If I am not wrong. 26(\d+) is the only number in that string
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Expression problem

Post by prometheuzz »

devendra-m wrote:If I am not wrong. 26(\d+) is the only number in that string
In THAT example there's no other number, but chances are that the OP is handling all kind of input which contain many different numbers since attributes within the tags the OP posted can contain numerical values. It would be like advising to take the sub-string of the characters on index 56 and index 57: it might work on the example input string the OP posted, but it will fail over-all.
Post Reply