regular expression

They have: 4 posts

Joined: May 2005

Hi, I hope someone can help me.

I'm using php.

Basically, I've captured a bunch of html in a variable, we'll call it $html

Now, I want to parse through the html and find every instance of
[some text]
then I want to look through "some text" and find all newlines (\n) and convert them to 's.

So, $html = preg_replace("reg exp","",$html);

I've been scratching my head and I just can't figure it out.

Thanks in advance.

Busy's picture

He has: 6,151 posts

Joined: May 2001

<?php
$newhtml
= eregi_replace(quotemeta(\"<address>\\0</address>\"),\"<address>\\0</address>\",$html);
/* doesn't really do anything, just converts the section to variable, will need
an array or loop if more than one instance */
$newhtml = str_replace(\"\n\",\"<br />\",$newhtml);
/*
$newhtml should be the orginal value with changes made */
?>

Try that, I haven't tested it but should work, note quotemeta() and \\0 should remain
Could also be done in a loop, but seems you only want to change \n to in certain areas

They have: 6 posts

Joined: Apr 2005

It almost works. It adds s to every newline regardless of where they are. So

hello world
<address>
23 blah
blah blah
</address>
'
becomes
hello world<br>
<address><br>
23 blah<br>
blah blah<br>
</address><br>
'

Thanks tho. Someone gave me a solution on another forum...

$string = <<<END
<address>
You and Yours
Your Home Address
Your Home State
</address>
END;

function ins_BR($arr){
return $arr[1].str_replace("\r\n", "<br />\n",$arr[2]).$arr[3];
}

$pattern = "/(<address>\r\n)+([^<]+)+(<\/address>)/";
echo preg_replace_callback($pattern, "ins_BR", $string);
'
which works fine excepts it adds a to the last line between the tags. If there are two lines, only the first should get the .

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

try:

<?php
echo preg_replace_callback(\"!<address>\s*(.+)\s*</address>!isU\", \"nl2br\", $string);
?>

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.