Make WordPress Core

Opened 17 years ago

Closed 16 years ago

#5624 closed enhancement (fixed)

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

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

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

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

Download all attachments as: .zip

Change History (8)

#1 @lloydbudd
17 years ago

  • Owner changed from anonymous to josephscott

#2 @DD32
17 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.

#3 @DD32
16 years ago

  • Keywords needs-patch added

#4 @Denis-de-Bernardy
16 years ago

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

#5 @FFEMTcJ
16 years ago

  • Milestone changed from 2.7.2 to 2.8

#6 @Denis-de-Bernardy
16 years ago

  • Keywords tested added

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

#7 @ryan
16 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.