RE: [PHP] help with regular expression
| From: | Michael Sims | Date: | Thu, 29 Jul 2004 18:22:03 +0000 |
| Subject: | RE: [PHP] help with regular expression | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-192233@lists.php.net to get a copy of this message | ||
Barbara Picci wrote:
> I've a script that must strip a string when it find the first word
> containing at least 4 characters; it must print the content of the
> string before that word, that word, a separator and the rest of the
> string.
>
> I've tried with ereg whit this script (#@# is the separator):
>
> ereg( '^([^ ]{4,})(.*)$', $testo, $matches);
>
> $contents = "$matches[1]#@#$matches[2]\n";
>
> but it is not the right script because if the strin($testo) is "the
> thing is" the script doesn't find nothing and doesn't print. For this
> example the right content of $contents must be:
>
> $contents = "the thing#@#is\n";
>
> instead of nothing.
I'm more comfortable with the PCRE functions:
$string = "the thing is";
if (preg_match('/^(.*?\S{4,})(\s*)(.*)$/', $string, $matches)) {
$contents = $matches[1].'#@#'.$matches[3]."\n";
print_r($contents);
}
prints
the thing#@#is
Your regex is anchoring its search for the first 4 character "word" to the beginning
of the string, which is probably not what you want.
I'm assuming from your description that you want whitespace that appears after the
first 4 character word to be replaced by the delimiter. Also you didn't specify
what should happen if the four character word happens to appear at the end of the
string. Also keep in mind that there are other word boundaries besides simply
whitespace, so you might want to use the "\w", "\W" metacharaters instead of
"\s"
and "\S". See "perldoc perlre" for more details...
HTH