Useful Regular Expression

This is a collection of useful regular expressions that I’ve found useful in doing some powerful manipulation of text, or extracting specific data.

//Validate domain
$url = "http://komunitasweb.com/";
if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
    echo "Your url is ok.";
} else {
    echo "Wrong url.";
}

source

// Remove carriage returns, line feeds and tabs
$text = str_replace(array("\r\n", "\r", "\n", "\t"), '', $text);

source

//Get all image urls from an html document
$images = array();
preg_match_all('/(img|src)\=(\"|\')[^\"\'\>]+/i', $data, $media);
unset($data);
$data=preg_replace('/(img|src)(\"|\'|\=\"|\=\')(.*)/i',"$3",$media[0]);
foreach($data as $url) {
	$info = pathinfo($url);
	if ( isset($info['extension']) ) {
		if (($info['extension'] == 'jpg') ||
		($info['extension'] == 'jpeg') ||
		($info['extension'] == 'gif') ||
		($info['extension'] == 'png'))
		array_push($images, $url);
	}
}

source

Scroll to Top