Pick out angle brackets

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
JKM
Forum Contributor
Posts: 221
Joined: Tue Jun 17, 2008 8:12 pm

Pick out angle brackets

Post by JKM »

Hi there!

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

Thanks.
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Pick out angle brackets

Post by jackpf »

Code: Select all

\<
Lol :P
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Pick out angle brackets

Post 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.
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Pick out angle brackets

Post 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 :)
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Pick out angle brackets

Post 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:
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Pick out angle brackets

Post 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...
Post Reply