Re: preg_replace anything that isn't WORD
| From: | Jonathan Tapicer | Date: | Sat, 22 Aug 2009 16:17:04 +0000 |
| Subject: | Re: preg_replace anything that isn't WORD | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-297083@lists.php.net to get a copy of this message | ||
Negating specific words with regexes isn't a good practice (see a deep
discussion here: http://www.perlmonks.org/?node_id=588315), in
your
case I would resolve it like this:
<?php
$s = 'cats i saw a cat and a dog';
var_dump(preg_split('/(dog|cat)/', $s, -1, PREG_SPLIT_DELIM_CAPTURE |
PREG_SPLIT_NO_EMPTY));
?>
That will output:
array(5) {
[0]=>
string(3) "cat"
[1]=>
string(10) "s i saw a "
[2]=>
string(3) "cat"
[3]=>
string(7) " and a "
[4]=>
string(3) "dog"
}
Then you just have to go through the result array of preg_split and
concatenate every "cat" and "dog".
Regards,
Jonathan
On Sat, Aug 22, 2009 at 12:32 PM, דניאל דנון<danondaniel@gmail.com> wrote:
> Lets assume I have the string "cats i saw a cat and a dog"
> i want to strip everything except "cat" and "dog" so the result will be
> "catcatdog",
> using preg_replace.
>
>
> I've tried something like /[^(dog|cat)]+/ but no success
>
> What should I do?
>
> --
> Use ROT26 for best security
>