note 112054 deleted from function.preg-match by aharvey

From: Date: Fri, 24 May 2013 17:11:17 +0000
Subject: note 112054 deleted from function.preg-match by aharvey
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-194900@lists.php.net to get a copy of this message
Note Submitter: Anonymous ---- here is a list of examples of php regular expressions. maybe this helps many people. ------------------------------------------------------- --------- PHP REGULAR EXPRESSIONS EXAMPLES ------- ------------------------------------------------------ preg_match does the search (preg_replace is a replacer). preg_match has three parameters - preg_match(FindWhat, FindWhere, GivingOutput); ===example 1)===: <?php //everything expect letters and numbers $text='abc345fg@h'; $newfilename=preg_match('/[^a-zA-Z0-9.]/',$text, $out); echo $out[0]; ?> output will be: @ preg_match finds only one result (the firstly found result), with two options: [0] or [1]. ===example 2)===: find everything (any characters,words..) inside our search criteria: <?php $text='abcdefghijklmnopqrst'; $newfilename=preg_match('/ij(.*?)mn/',$text, $out); echo $out[0]; echo $out[1]; ?> [1] -gives only the inner search result (what we had in the brackets, between "ij" and "mn"): kl [0] -gives the whole search result: ijklmn (Note, that option [1] is not avaiable if when you dont use brackets in search criteria (as we have above, in example 1) ===example 3)===: if your target text has many same occurences, like this: $text='hello user ===Jimmy Jones===, its me. hello user ===Mery Pawders===, its still me.'; now, here are two different matches, so, we need to use preg_match_all <?php $text='hello user Jimmy Jones, its me. hello user Mery Pawders, its me.'; $newfilename=preg_match_all('/hello user (.*?) its/',$text, $out); foreach ($out[1] as $found_one) {echo $found_one;} //or use $out[0] for full search match ?> output will be: Jimmy Jones, Mery Pawders, ===example 4)===: search among many possibilities: <?php $text = 'member ACCOUNT7'; preg_match("/ACCOUNT[123456789]/",$text,$out); echo $out[1]; ?> output will be: ACCOUNT7 ===example 5)===: To find a string, while input text contains new lines, you must use===s=== at the end; <?php $text = 'one two three'; preg_match("/one(.*?)three/s",$text,$out); echo $out[1]; ?> output will be: two ===example 6)===: Your search is always case sensitive. To make a case INSENSITIVE search, use ===i=== at the end (if you want, without ===s===); <?php $text = 'ONE TWO TREE'; preg_match("/one(.*?)three/si",$text,$out); echo $out[1]; ?>

« previous php.notes (#194900) next »