2009
08.22

Fun with RegEx.

Well, it’s Saturday. Instead of sleeping, I’ll do something relatively useful. Which I’ve been failing miserably at doing as of late. Oh well. Enjoy.

Get rid of duplicate text

This can be useful for quie a few things. I used it to remove duplicate emails. You can even configure it to re-write the text file, if you do a bit of Googleing.

1
2
3
$text = file_get_contents('../info/emails.txt'); //grab the contents
$textMinusDups = preg_replace("/s(w+s)1/i", "$1", $text); //get rid of duplicates
echo($textMinusDups); //echo the rest

Highlight Text

This could be used for search results, most likely. But you can find something to suit your needs. Hell, with a little Ajax, you could make yo own CTRL+F function. Of course, I don’t condone using keystrokes on websites.

1
2
3
$words = 'Some say \'Jesus Saves\', but they don\'t know. One day their Magic Marker signs will say \'Mr. Evil pwns.\'';
$highlightFind = preg_replace("/b(Mr. Evil pwns.)b/i", '<span style="background:#ff0000;color:#fff;font-size:300px">1</span>', $words);
echo $highlightFind;

Grab All Images

I’m havin trouble thinking of any way this could be useful for images only, but someone can. Expandable to any file extension

1
2
3
4
5
6
7
8
9
10
11
12
$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);
		}
	}
}

Grab Page Title

I would use this for bookmarking. You know, user inputs URL, script saves it, and grabs the page title. I digress. Have fun.

1
2
3
4
5
6
$grabPage = fopen("http://www.mrevil.feedthedragon.net","r");
while (!feof($grabPage)){ $page .= fgets($grabPage, 4096); }
 
$title = eregi("<title>(.*)</title>",$page,$regs);
echo $regs[1];
fclose($grabPage);

BBCode Smilies

This is wicked simple. And chances are, if you have a use for it, you already know how to do it. Oh well.

1
2
$text = '[:-)]';
echo str_replace('[:-)]','<img src="smilies/smile.png">',$text); // convert [:-)] to the image

No Comment.

Add Your Comment

You must be logged in to post a comment.

Easy AdSense by Unreal