emehrkay Posted April 2, 2008 Share Posted April 2, 2008 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" Quote Link to comment Share on other sites More sharing options...
effigy Posted April 2, 2008 Share Posted April 2, 2008 I would open up the contents: $find = '/'. preg_quote($attribute) . '\s*=\s*"[^"]*"/'; Are you always going to be working with double quoted attributes? Quote Link to comment Share on other sites More sharing options...
emehrkay Posted April 2, 2008 Author Share Posted April 2, 2008 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'); Quote Link to comment Share on other sites More sharing options...
effigy Posted April 2, 2008 Share Posted April 2, 2008 For now: $pattern = '/"[^"]*"/'; Quote Link to comment Share on other sites More sharing options...
emehrkay Posted April 2, 2008 Author Share Posted April 2, 2008 Awesome, it worked. I had to add prens around the pattern though $pattern = '/"([^"]*)"/'; Thanks a lot. \w clearly means word and a hash isnt a word. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.