regex confused by > in anchor data-caption property
-
After hacking photoswipe gallery to call apply_filters(), I ran into trouble with this plugin. I had put markup in the captions for the gallery, which showed up in the anchor tag as a data-caption property.
Having that stuff there made the regex for add_property() and add_class() miss the actual > at the end of the anchor tag. I modified your code as follows to overcome this particular problem:
// just like add_property except if there is are classes already the new value is appended rather than replacing the old private static function add_class( $needle, $class, $output ) { return self::add_property($needle, 'class', $class, $output, true); } // End function add_class() private static function add_property( $needle, $property_name, $property_value, $output, $append = false ) { // Clean up our needle for regexing $needle = preg_quote( $needle ); // Clean property values a bit $property_name = esc_attr( $property_name ); $property_value = esc_attr( $property_value ); // find the anchor tag with the href we care about preg_match('@<a.*?href\s*=\s*["\']('.$needle.')(.).*</a>(.)@Us', $output, $matches, PREG_OFFSET_CAPTURE); // check if the tag already has the property if (preg_match('@'.preg_quote($property_name).'\s*=\s*"([^"]*)(")@Us', $anchor_tag, $prop_matches, PREG_OFFSET_CAPTURE)) { $anchor_tag = $matches[0][0]; if ($append) { $replace_start = $replace_end = $prop_matches[2][1] - 1; } else { $replace_start = $prop_matches[1][1]; $replace_end = $prop_matches[2][1]; } $anchor_tag = substr($anchor_tag, 0, $replace_start).' '.$property_value.substr($anchor_tag, $replace_end); $output = substr($output, 0, $matches[0][1]) . $anchor_tag . substr($output, $matches[3][1]); } else { $output = substr($output, 0, $matches[2][1] + 1) . ' ' . $property_name .'="' . $property_value . '"' . substr($output, $matches[2][1]+1); } return $output; } // End function add_property()
(hopefully I can edit this if the formatting is hosed)
This solved my immediate problem, but will now probably if the name of the property is in the text of the link itself. So, for instance if I use the phrase “class =” in the text of a link, this might break. Still, it’s a move in the right direction, I believe.
- The topic ‘regex confused by > in anchor data-caption property’ is closed to new replies.