Regular expression to insert a space in front of all '<' characters but not </div> I have tried with one like this preg_replace("/<[\/div>]/", " <", $txt); Code (markup): but not working
Thanks for the reply but still it is not working. $txt = "tst<i> THIS IS TEST</div> pgm"; $txt = preg_replace("/<[^\/div>]/", " <", $txt); Code (markup): o/p tst<i> THIS IS TEST</div> pgm (need space in front of <i> but not in </div>)
You need to use a Lookahead Assertion. <?php $str = array(); $str[] = '<i>'; $str[] = '</div>'; $str[] = '</i>'; foreach($str as &$st) { $st = preg_replace('#<(?!/div)#', ' <', $st); echo htmlentities($st) . '<br/>'; } ?> Code (markup):
This should do the trick: preg_replace("\<~(\/div\>)", " <", $txt); Code (markup): Hope this helps EDIT - A lookahead is not required to do this, plus it takes it much longer when performing lookahead and lookbehind Regex searches, the Regex I provided will match EVERY '<' where it is not followed by '/div>' and replace it with ' <'. But are you aware that this will pick up here as well, selected in bold: <p>This is a paragraph</p>
You sure about that red-sky ? Even if I add pattern delimiters to get past the syntax errors, I still can't get what you posted to work. I'm not even sure about the logic behind it.
Actually you may be right, I only realised that this was in a PHP subforum, the Regex I wrote was for VB.NET, sorry about that
it is not possible to place the entire html tags in array and check because we can't predict the number of html elements in a page. any other soln?
I think he believes his tags have to be in an array to be alidated with a regular expression, you can run the Regex through your whole html source code, it doesn't have to be stored in arrays. Actually I have no idea about Regex's in PHP so im gonna stop confusing people . But can you confirm if it's the same with PHP jobert? Thats exactly what it does, VB.NET has limited Regex functionality, but of what's there is can be very powerful.
Maybe the way I presented the example code was confusing with that array & instead of an actual space ? Here's an example using the test string in an earlier post. $str = "tst<i> THIS IS TEST</div> pgm"; $str = preg_replace('#<(?!/div)#', ' <', $str); Code (markup): Now, if you want it not to match any closing tags, for instance match <i>, <b>, but not </i>, </b>, etc, you can still use close to the same code, substituting the DIV for a character class consisting of letters & a finishing angle-bracket. $str = "start<div>tst<i> THIS IS TEST</i></div> pgm"; $str = preg_replace('#<(?!/[a-z]+>)#', ' <', $str); Code (markup): Now I really do have no idea what to try if that's not it.