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"

Link to comment
Share on other sites

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');

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.