Make WordPress Core

Opened 8 years ago

Closed 6 years ago

#5624 closed enhancement (fixed)

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

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


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 (1)

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

Download all attachments as: .zip

Change History (8)

comment:1 @lloydbudd8 years ago

  • Owner changed from anonymous to josephscott

comment:2 @DD328 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 @DD327 years ago

  • Keywords needs-patch added

@Denis-de-Bernardy7 years ago

comment:4 @Denis-de-Bernardy7 years ago

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

comment:5 @FFEMTcJ7 years ago

  • Milestone changed from 2.7.2 to 2.8

comment:6 @Denis-de-Bernardy6 years ago

  • Keywords tested added

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

comment:7 @ryan6 years ago

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

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

Note: See TracTickets for help on using tickets.