Page 1 of 1

Pick out angle brackets

Posted: Sun Aug 02, 2009 4:24 pm
by JKM
Hi there!

How do I pick out angle brackets (<>) with regex? It's for preg_replace.

Thanks.

Re: Pick out angle brackets

Posted: Sun Aug 02, 2009 4:28 pm
by jackpf

Code: Select all

\<
Lol :P

Re: Pick out angle brackets

Posted: Mon Aug 03, 2009 2:01 am
by prometheuzz
jackpf wrote:

Code: Select all

\<
Lol :P
'<' an '>' are no meta characters, so there's no need to escape them:

Code: Select all

$s = 'abc < def';
echo preg_replace('/</', '', $s);
@OP: You sure you need preg_replace? A simple replacement of a certain (fixed) character can also be done using str_replace.

Re: Pick out angle brackets

Posted: Mon Aug 03, 2009 7:25 am
by jackpf
prometheuzz wrote:'<' an '>' are no meta characters, so there's no need to escape them:
Ahh right, I wasn't sure. I normally escape all non-alphanumeric characters in regex just to be sure. Better safe than sorry :)

Re: Pick out angle brackets

Posted: Mon Aug 03, 2009 7:47 am
by prometheuzz
jackpf wrote:
prometheuzz wrote:'<' an '>' are no meta characters, so there's no need to escape them:
Ahh right, I wasn't sure. I normally escape all non-alphanumeric characters in regex just to be sure. Better safe than sorry :)
I partly agree with you: it is indeed good to be cautious, but overly escaping characters that need not be escaped will make your regex (even) more complicated to read. :wink:

Re: Pick out angle brackets

Posted: Mon Aug 03, 2009 8:16 am
by jackpf
Very true....

But at least, when you're facing problems like this, it won't do any harm to escape all non-alphanumeric characters to see what your problem is...