Re: [Newbie] Questions...

From: Date: Thu, 08 May 2003 23:35:58 +0000
Subject: Re: [Newbie] Questions...
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-146935@lists.php.net to get a copy of this message
At 01:20 09.05.2003, The Head Sage said: --------------------[snip]-------------------- >I've read the manual entry on preg_replace() and i've used google for help >but i'm still confused as it all looks horribly complicated.. > >What i want to do is when a user submits a quote for example "<@TheHeadSage> >lol" i want to remove the <>'s and replace them with &lt; and &gt; so >they >display properly on a webpage. How would i go about this using >preg_replace() or another function like it? RE's are a quite fine thing when you look at what you're really going to do. Having your example I'd say you want to replace any (sub)string starting with '<@', having one or more alphanumeric characters, and ending in '>', with '&lt;@' + whatever_in_between + '&gt;'. Ok, this is the regex for it: $string = preg_replace('/<(@[a-z0-9]+?)>/i', '&lt;$1&gt;', $string); This regex explained: < beginning with a '<' ( open a group @ next char is a '@' [a-z0-9]+? one or more of the characters between [], but stop matching when encountering the next: ) end this group > pattern must end with a '>' and replace it with &lt; as-is $1 the first group from the previous regex &gt; as-is The 'i' modifier of the regex tells preg to do a case-insensitive match. The '?' after the character set tells preg to do a non-greedy match. By default preg is greedy, that is it matches as much characters as possible. While this is meaningless in this example (a '>' would terminate the match anyway because it is not contained within the character set), having this charset '.+' (one or more of _any_ character) will make it work. As an example: Using '/<@(.+)>/' Matching against 'I saw <@AWhiteShark> <@or> <@some other> fish' will result in 'I saw &lt;@AWhiteShark> <@or> <@some other&gt; fish'. Using '/<@(.+?)>/' will correctly produce 'I saw &lt;@AWhiteShark&gt; &lt;@or&gt; &lt;@some other&gt; fish'. Hope this helps. -- >O Ernest E. Vogelsinger (\) ICQ #13394035 ^ http://www.vogelsinger.at/

« previous php.general (#146935) next »