Log in

View Full Version : Another Reg Ex Q



bluewalrus
01-22-2010, 04:23 AM
Is there a way using the preg_replace to find the same value from the first find. For example I think it'd be similiar to this



</(.*)>(.*)<$1>


I'm trying to find the closing and opening of html tags. For example I have miscoded pages and I need to correct them

Miscoded page looks like:


</li>
Text in the wrong side<li>


Thanks.

techietim
01-22-2010, 11:31 AM
This documentation (http://php.net/manual/en/regexp.reference.back-references.php) should help you out.

Basically, just replace that $1 with a \1.

bluewalrus
01-22-2010, 02:09 PM
Thanks. That works in dreamweaver but not on my page, any idea? I'm currently trying to get rid of misplaced line breaks.


$patterns[30] = '/<(.*)>(.*)<\/\1><br \/>/';
$replacements[30] = '<$1>' . "$2" . '</$1>';


<li>This is an example.</li><br />

To this:

<li>This is an example.<li>

james438
01-25-2010, 05:28 AM
Is this what you are looking for?


<?php
$test="<li>this is a test</li>
<br>this should not be here.
<li>good</li>";
$test=preg_replace('/(<\/)(.*?)(>)(.*?)(<\2>)/s','$1$2$3$5',$test);
echo "$test";
?>

It's sloppy, but should do the trick.

bluewalrus
02-15-2010, 03:47 AM
Got another one


$patterns = array();
$patterns[0] = '/<' . "$browser" . '>(.*)' ."<\/$browser>" . '/';
$replacements = array();
$replacements[0] = "<$browser>" . '$1 + 1' . "</$browser>";
echo preg_replace($patterns, $replacements, $stats);

How can I added 1 to the first value here?

this currently just echos out the first value and + 1. Thanks.

james438
02-15-2010, 07:29 AM
I am being lazy with my answer tonight. Partly because I have not worked much with arrays in PCRE code. The other reason is because I don't have all of the information like the string you are working with or what $browser is or $stats is.

I think I can still help though. What you need to do here is use the e modifier (http://php.net/manual/en/reference.pcre.pattern.modifiers.php). Take a look at the following example:


<?php
$text="div1div2div3div4div5div6div7div";
$text=preg_replace('/v(.*?)d/e',"v.($1+1).d",$text);
echo"$text";
?>

this will produce:

div2div3div4div5div6div7div8div

The e modifier will allow you to insert php into your regular expression whether it be a strtoupper function or str_replace function. The syntax involved is a little different though. Commands and captured substrings in the replacements are concatenated with a period. Captures are generally placed within single quotes or parentheses.

I am a little unclear as to the exact syntax used when using the e modifier and php.net is not as clear on the matter as I would hope. In fact it is quite vague. If anyone wants to add to or correct what I have said in this post please do.