Useful PHP regular expressions for web developers
Validate domain name
Verify if a string is a valid domain name.
$url = "/";
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.";
}
Mark a word from a text
This very useful regular expression find a specific word in a text, and mark it. Extremely useful for search results.
$text = "regex has become popular in web programming.";
$text = preg_replace("/b(regex)b/i", '<mark>1</mark>', $text);
echo $text;
Get all images from a 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);
}
}
Remove repeated words (case insensitive)
$text = preg_replace("/s(w+s)1/i", "$1", $text);
Remove repeated punctuation
$text = preg_replace("/.+/i", ".", $text);
Matching a XML/HTML tag
This simple function takes two arguments: The first is the tag you’d like to match, and the second is the variable containing the XML or HTML.
function get_tag($tag, $html) {
$tag = preg_quote($tag);
preg_match_all('{<'.$tag.'[^>]*>(.*?)</'.$tag.'>.'}',
$html,
$matches,
PREG_PATTERN_ORDER);
return $matches[1];
}
Matching an HTML/XML tag with a certain attribute value
This function is very similar to the previous one, but it allow you to match a tag having a specific attribute. For example, you could easily match <div id=”header”>
function get_tag( $attr, $value, $xml, $tag=null ) {
if( is_null($tag) )
$tag = 'w+';
else
$tag = preg_quote($tag);
$attr = preg_quote($attr);
$value = preg_quote($value);
$tag_regex = "/<(".$tag.")[^>]*$attrs*=s*".
"(['"])$value2[^>]*>(.*?)</1>/"
preg_match_all($tag_regex,
$xml,
$matches,
PREG_PATTERN_ORDER);
return $matches[3];
}
Matching hexadecimal color values
Another interesting tool for web developers! It allows you to match/validate a hexadecimal color value.
$string = "#555555";
if (preg_match('/^#(?:(?:[a-fd]{3}){1,2})$/i', $string)) {
echo "example 6 successful.";
}
Find page title
This handy code snippet will find and print the text within the <title> and </title> tags of a html page.
$fp = fopen("/blogs","r");
while (!feof($fp) ){
$page .= fgets($fp, 4096);
}
$titre = eregi("<title>(.*)</title>",$page,$regs);
echo $regs[1];
fclose($fp);
Generating automatic smileys
Another function used by WordPress, this one allow you to automatically replace a smiley symbol by an image.
$texte='A text with a smiley :-)';
echo str_replace(':-)','<img src="smileys/souriant.png">',$texte);
Remove carriage returns, line feeds and tabs
$text = str_replace(array("
", "
", "
", " "), '', $text);
Clean up a sentence end that has no trailing space
$text = preg_replace("/.(?! )/i", ". ", $text);
Comments 0