Page 1 of 1

Function: regex_escape_string()

Posted: Mon Jul 18, 2005 1:17 pm
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';

Posted: Fri Jul 22, 2005 4:33 pm
by Chris Corbyn
I'm such a dumb-ass....

http://www.php.net/preg_quote

:oops:

group hug, group hug :P

Posted: Sat Jul 23, 2005 11:31 am
by John Cartwright
praise the manual.

Posted: Sat Jul 23, 2005 11:34 am
by timvw
Bless you!