Ticket #5624 (closed enhancement: fixed)

Opened 4 years ago

Last modified 3 years ago

Calls to preg_replace() after preg_match() in functions.php may be unnecessary

Reported by: bernzilla Owned by: josephscott
Priority: normal Milestone: 2.8
Component: Optimization Version:
Severity: minor Keywords: has-patch tested
Cc: Bernzilla

Description

I noticed that in functions.php (which comes with the WordPress.org install) there are at least a few instances where PHP's preg_replace() function is used to remove excess information to narrow in on a subset searched for in a preceding call to preg_match().

Unless there is a specific reason for relying on preg_replace() in these instances, it might be better to rely on the subpattern match instead of the full string match, so that calls to preg_replace() can be avoided altogether.

Consider the following example:

function xmlrpc_getposttitle($content) {
	global $post_default_title;
	if ( preg_match('/<title>(.+?)<\/title>/is', $content, $matchtitle) ) {
		$post_title = $matchtitle[0];
		$post_title = preg_replace('/<title>/si', '', $post_title);
		$post_title = preg_replace('/<\/title>/si', '', $post_title);
	} else {
		$post_title = $post_default_title;
	}
	return $post_title;
}

The same effect can be accomplished by simply originally setting the $post_title variable to the subpattern match, like so:

function xmlrpc_getposttitle($content) {
	global $post_default_title;
	if ( preg_match('/<title>(.+?)<\/title>/is', $content, $matchtitle) ) {
		$post_title = $matchtitle[1];
	} else {
		$post_title = $post_default_title;
	}
	return $post_title;
}

There may be other places in functions.php (or other files) where the same paradigm is employed. If so, they could likely benefit from this change as well.

It's a minor thing, but I figured I'd point it out anyway.

Attachments

5624.diff Download (693 bytes) - added by Denis-de-Bernardy 3 years ago.

Change History

  • Owner changed from anonymous to josephscott

comment:2   DD324 years ago

+1, even using str_replace() would make more sense in this particular case if theres a reason the preg_match() submatches cant be relied upon.

comment:3   DD323 years ago

  • Keywords needs-patch added
  • Keywords has-patch added; needs-patch removed
  • Milestone changed from 2.9 to 2.7.1
  • Milestone changed from 2.7.2 to 2.8
  • Keywords tested added

haven't tested against the latest trunk, but it worked fine when I uploaded it

comment:7   ryan3 years ago

  • Status changed from new to closed
  • Resolution set to fixed

(In [11024]) Eliminate unecessary preg_replace. Props bernzilla, Denis-de-Bernardy. fixes #5624

Note: See TracTickets for help on using tickets.