Reply to Re: RegExp : using end-of-line in a pattern

Your name:

Reply:


Posted by Chung Leong on 09/21/05 20:27

I would recommend using the Perl compatible regexp functions over the
POSIX ones. They're faster and more powerful. People also tend to be
more familiar with the Perl syntax.

The following snippet does what you want:

<?
$s = "
Name: Mr Smith
Address: Paris
";
preg_match_all('/^(.+?): (.+?)$/m', $s, $m, PREG_SET_ORDER);
foreach($m as $set) {
echo "{$set[1]} = {$set[2]}<br>";
}
?>

The m modifier at the end tells the regexp engine to treat newline as
end of line. The ^ assertion, which normally would only match the
beginning of the string, now match sees a match immediately following
at newline. The same for the $ end-of-line assertion.

The (.+?) parts mean capturing at least one character, with greediness
turned off. Greediness dictates whether the regexp engine will try to
find the longest possible match. We don't want it to be greedy here.
Given the string "Time: 8:00PM", for example, we want the engine to
match up the first colon and stop, instead of trying to find another
colon that'd yield a longer match.

In an actual programming situation I would use the following pattern to
deal with possible errant white spaces:

/^\s*(.+?)\s*:\s*(.+?)\s*$/m

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация