Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regular expression doesnt work as expected

Status
Not open for further replies.

daneharnett

Programmer
May 26, 2003
39
0
0
AU
Hi everyone,
im trying to use ereg() to match a pattern in a string.
my pattern is "(.*) (.*)"
my string is "foreach ($x as $i)"
basically i would like to get the first string up until the first 'space' char..
when i ereg these via
ereg($pattern, $string, $matches);

$matches[1] = "foreach ($x as";

i want it to only be "foreach";

can anyone help?
 
That's because regular expressions are greedy. They are supposed to capture as much of the string as possible while fulfilling the terms of the expression. Since you basically told the regex engine, "Split the string at the space", the first "(.*)" grabbed as much as it could.

For something that simple, I wouldn't use a regular expression -- I'd just use split(). This code:

Code:
<?php
$a = 'foreach ($x as $i)';

$b = split (' ', $a, 2);

print_r ($b);
?>

Will output:

Code:
Array
(
    [0] => foreach
    [1] => ($x as $i)
)




Want the best answers? Ask the best questions: TANSTAAFL!!
 
yup or u can use the /U modifier (i use it along with preg)
preg_match_all(&quot;/(.*)\s/U&quot;, $string, $matches);

does it work?


Known is handfull, Unknown is worldfull
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top