PDA

View Full Version : PHP perl and pattern matching



james438
06-01-2007, 03:21 AM
I'm kinda new to PHP's pattern matching function.

here is the working code:


$two="/\r\n\r\n/"
$summary=htmlentities($summary);
$summary=preg_replace("$two","Ý",$summary);
$summary=preg_replace("/&#221;+/","<br><br>",$summary);
$summary=html_entity_decode($summary);
$summary=preg_replace("/<p>/","",$summary);

What I want to do is something like this


$summary=preg_replace("/\r\n\r\n+/","<br><br>",$summary);

where the '+' is applied to \r\n\r\n and not just \n. In the first example I converted it to a weird character like &#221; and applied the '+' to that instead and then reconverted the chained occurances of &#221; to a single occurance of <br><br>.

For visitors who are a bit lost here and is a short explanation of some of the terms:

\r = a carriage return. A carriage return is what happens when you want to go down a line and to the left using an old fashioned type writer.
\n = newline. it goes directly down a line.
When typing a web document the enter button creates two non-printing characters /r/n that both occur together for some reason.
preg_replace replaces all occurances of a term from a string.
html_entity_decode and htmlentities are just ways to convert a web file into a different format like making < appear as &lt; instead.

james438
06-10-2007, 10:27 PM
any ideas?

Twey
06-10-2007, 10:48 PM
I think str_replace("\r\n\r\n", '<br>', $summary) would do as well... or maybe I'm misunderstanding you.

james438
06-11-2007, 12:57 AM
Well, I am trying to get the '+' to be applied to all of /r/n/r/n.

No worries, this isn't really very important. I found a workaround, but I figure there must be a way to do it.

Thanks for looking into it.

mburt
06-11-2007, 01:15 AM
When using the function str_replace() is searches all global occurences anyways. It doesn't take a regular expression as a parameter.

james438
06-11-2007, 03:00 PM
but what if I wanted one ;)

what if I wanted it to recognize chained occurances of carriage returns, but only if the chain is 2 occurances or more or between 2 and 5 long, but if it is more than 5 then it will be ignored?

I have been teaching myself from these two sites here (http://us.php.net/manual/en/reference.pcre.pattern.syntax.php) and here (http://zvon.org/other/PerlTutorial/Output/regexps.html). In particular this link (http://zvon.org/other/PerlTutorial/Output/example12.html#case2) shows how to recognize chained occurances of something, but I have not figured out how to get it to recognize chained occurances of /r/n/r/n as opposed to just /s, which is pretty easy, because i just add a + to make it /s+ so that it will recognize chained white space.

Twey
06-11-2007, 04:47 PM
'/((:?\r\n){2, 5})/g'will match "\r\n" repeated between two and five times.

james438
06-11-2007, 08:34 PM
thanks,

it was kind of a silly thing, but I was curious :)