Replacing Placeholder Variables in a String

I think for such a simple task you don’t need to use RegEx: $variables = array(“first_name”=>”John”,”last_name”=>”Smith”,”status”=>”won”); $string = ‘Dear {FIRST_NAME} {LAST_NAME}, we wanted to tell you that you {STATUS} the competition.’; foreach($variables as $key => $value){ $string = str_replace(‘{‘.strtoupper($key).’}’, $value, $string); } echo $string; // Dear John Smith, we wanted to tell you that you … Read more

PHP preg_match to find whole words

preg_match(‘/\b(express\w+)\b/’, $string, $matches); // matches expression preg_match(‘/\b(\w*form\w*)\b/’, $string, $matches); // matches perform, // formation, unformatted Where: \b is a word boundary \w+ is one or more “word” character* \w* is zero or more “word” characters See the manual on escape sequences for PCRE. * Note: although not really a “word character”, the underscore _ is … Read more

PHP – regex to allow letters and numbers only

1. Use PHP’s inbuilt ctype_alnum You dont need to use a regex for this, PHP has an inbuilt function ctype_alnum which will do this for you, and execute faster: <?php $strings = array(‘AbCd1zyZ9’, ‘foo!#$bar’); foreach ($strings as $testcase) { if (ctype_alnum($testcase)) { echo “The string $testcase consists of all letters or digits.\n”; } else { … Read more

Optional Whitespace Regex

Add a \s? if a space can be allowed. \s stands for white space ? says the preceding character may occur once or not occur. If more than one spaces are allowed and is optional, use \s*. * says preceding character can occur zero or more times. ‘#<a href\s?=”https://stackoverflow.com/questions/14293024/(.*?)” title\s?=”https://stackoverflow.com/questions/14293024/(.*?)”><img alt\s?=”https://stackoverflow.com/questions/14293024/(.*?)” src\s?=”https://stackoverflow.com/questions/14293024/(.*?)”[\s*]width\s?=”150″[\s*]height\s?=”https://stackoverflow.com/questions/14293024/(.*?)”></a>#’ allows an optional … Read more

PHP preg_match to find multiple occurrences

You want to use preg_match_all(). Here is how it would look in your code. The actual function returns the count of items found, but the $matches array will hold the results: <?php $string = “/brown fox jumped [0-9]/”; $paragraph = “The brown fox jumped 1 time over the fence. The green fox did not. Then … Read more