Page 1 of 1

Conditional Matching

Posted: Thu Oct 01, 2009 1:47 am
by HiddenS3crets
The goal of my preg_replace code is this: if a line begins with a bold, italic or underline tag opener (i.e. <b> <u> <i>) OR begins with NO tag, wrap the line in a <p> tag.

This means that lines that begin with <div.., <ul>, <li>, etc will not have a paragraph tag put around them.

How can I structure the regex to match either a opening b, u, or i tag, or no tag at all?

Examples

Code: Select all

This is a line of text with no tags around it.
 - regex will put <p> around this line
 
<b>this is some bold text</b>
 - regex will put <p> around this line too
 
<li>this is a list item</li>
 - regex will NOT put a <p> tag around this line

Re: Conditional Matching

Posted: Thu Oct 01, 2009 2:36 am
by prometheuzz
Try something like this (not properly tested!):

Code: Select all

$html ='<b>dsf</b>
 
text
 
<u>dfsdf
fds
fds</u>
 
<i>fgdfg
gfd
gf\

Re: Conditional Matching

Posted: Sat Oct 10, 2009 12:26 pm
by ridgerunner
This one should do the trick:

Code: Select all

// regex: long commented version
$re_long = '/
^            # anchor regex to beginning of line
(            # capture whole line into group 1
[ \t]*+      # allow optional leading whitespace
  (?=        # make sure the line begins with...
    <[bui]>  # a <b>, <u> or <i>
  |          # or...
    [^<\s]   # a non-tag, non-whitespcase char
  ).++       # if so, match whole (non-empty) line
)            # end capture group 1
$            # anchor regex to end of line
/mx';
 
// regex: short uncommented version
$re_short = '/^([ \t]*+(?=<[bui]>|[^<\s]).++)$/m';
 
$text = preg_replace($re_short, '<p>$1</p>', $text);
Edited 2009-10-11 7:55am MDT: Added optional leading whitespace