Function: regex_escape_string()

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Function: regex_escape_string()

Post by Chris Corbyn »

Extremely handy if you're regularly building patterns using external input. This *should* prevent problems with dodgy characters ending up in the string. Shout me if you spot I missed something or it bugs out on ya!

If you're using a delimiter other than "/" then give it as the second parameter ;)

Code: Select all

<?php

/*
 Written by d11wtq of http://forums.devnetwork.net/
 
 regex_escape_string(string string [, string delimiter])
 
 Escapes the relevant characters in a string in preparation
 -- for including in a regex pattern.
 
 2005-07-18
 */

function regex_escape_string($string, $delimiter='/') {

	$nasties = array ( //Stuff to always escape
		'.',
		'?',
		'*',
		'+',
		'-',
		'^',
		'$',
		'(',
		')',
		'[',
		']',
		'{',
		'}',
		'\\',
		'|'
	);
	
	$nasties[] = $delimiter; //Whatever delimiter is being used
	
	$goodies = array();
	foreach ($nasties as $v) {
	
		$goodies[] = '\\'.$v; //Escaped versions
		
	}
	
	$string = str_replace($nasties, $goodies, $string); //Fix the string
	
	return $string;
	
}

?>
It's clear enough but here's an example:

Code: Select all

$input = 'http://www.foo.bar/page.htm#bob';
$pattern = '#\\w+(\\d*?)56 '.regex_escape_string($input, '#').'$#is';
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

I'm such a dumb-ass....

http://www.php.net/preg_quote

:oops:

group hug, group hug :P
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

praise the manual.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Bless you!
Post Reply