Jump to content

my little replace function is breaking on the hash '#'


emehrkay

Recommended Posts

I just wrote a function that will take a string of html attributes

 

"class="whatever class" alt="alt_Text"' etc

 

But, I just noticed that it breaks when I pass in a string containing the hash mark

 

'href="#" class="test"'

 

Any idea how to fix this?

 

Thanks

 

function addReplaceAttributes($attributes_string, $attribute, $new_property, $append = true){		
$find 			= '/'. $attribute .'\\ *=\ *+\"+[a-zA-Z1-9\.]+\"/';

if(preg_match($find, $attributes_string, $matches)){		
	$pattern 		= '/\"(\w+)\"/i';
	$replace 		= ($append) ? '"$1 ' . $new_property .'"' : '"'. $new_property .'"';
	$new_attribute 	= preg_replace($pattern, $replace, $matches[0]);

	return preg_replace($find, $new_attribute, $attributes_string);
}else{
	return $attributes_string .' '. $attribute .'="'. $new_property .'"';
}
}

echo addReplaceAttributes('href="#xxx" class = "class" ', 'class', 'this_is_a_new_one_added');
//returns href="#xxx" class = "class"

Not necessarily. My regex is very amateur hour.

 

I've updated with your suggestion, still no dice when tyring to change the href

 

function addReplaceAttributes($attributes_string, $attribute, $new_property, $append = true){		
	$find = '/'. preg_quote($attribute) . '\s*=\s*"[^"]*"/';

	if(preg_match($find, $attributes_string, $matches)){
		$pattern 		= '/\"(\w+)\"/i';
		$replace 		= ($append) ? '"$1 ' . $new_property .'"' : '"'. $new_property .'"';
		$new_attribute 	= preg_replace($pattern, $replace, $matches[0]);

		return preg_replace($find, $new_attribute, $attributes_string);
	}else{
		return $attributes_string .' '. $attribute .'="'. $new_property .'"';
	}
}

echo addReplaceAttributes('href="#xxx" class = "class" ', 'href', 'this_is_a_new_one_added');

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.