Why doesn't this preg_replace work?

Theres something I’m missing, could someone enlighten me? For some reason it just WONT replace the spaces with dashes. The titler function works outside of the bbcode class, formats the string inside the bbcode class fine, but won’t swap out the spaces! WRYYY!
titler.php:
[php]<?php
class BBCode{
public function parse($str) {

    $simple_search = array(
                            '/\[title\](.*?)\[\/title\]/is',
                            '/\[highlight\](.*?)\[\/highlight\]/is',
                            '/\[anchor\](.*?)\[\/anchor\]/is',
                            );

    $simple_replace = array(
                            $this->titler('\\1'),
                            '<span class="highlight">$1</span>',
                            '<a name="$1"></a>',
                            );
	$str = preg_replace ($simple_search, $simple_replace, $str);
    return $str;
}


public function titler($in){
	$sec = preg_replace("@\s@is", "-", $in);
    $out = '<a name="'.$sec.'" href="#'.$sec.'"><span class="title">'.$in.' - &gt;</span></a>';
	return $out;
}	

}
?>[/php]
titler.php
[php]<?php
include_once(“titler.php”);
$bbcode = new BBCode();
$txt = $bbcode->parse("[title]this is a test[/title]some words

omg HTML

");
echo $txt;
?>[/php]

thanks for reading. =]

Ran this by a few of my friends, we all googled around, maybe we’re thinking of the wrong keywords, still can’t figure it out!

What spaces are you talking about ? :smiley:

Yes…Context.

The spaces in the string captured from the title bbcode, which is then inserted into the tag hyphenated in the href and name, but not in the innerHTML of the tag. The hyphens do not appear as they should per the line:
[php]$sec = preg_replace("@\s@is", “-”, $in);[/php]

Again, the titler function WORKS (as in inserts hyphens appropriately) when called directly, but doesnt when called through as a preg_replacement.

The anticipated output being:

<a name="this-is-a-test" href="this-is-a-test">this is a test</a>

::slight_smile:

by the time the string gets to the titler function, $in = \1. Meaning that the string doesnt get passed to the function and therefor cant be preg_replaced.

I’ll find a workaround but…Can anyone answer why?

[php]$str = preg_replace_callback(
‘@@is’,
create_function(
‘$matches’,
‘$split = explode(" “,$matches[1]);
$sec = implode(”-",$split);
return “<a name=”$sec" href="#$sec">";’
),$str);[/php]

Solved.

Sponsor our Newsletter | Privacy Policy | Terms of Service