PHP preg_match() and regex

by koesbong on March 5, 2011

While working on a personal project today, I learned something quite interesting. This might be a common knowledge, but it’s totally new to me.

<?php
$pattern = "/\$[\d]+\.?[\d]{0,2}/";
preg_match($pattern, "text $50 more 234", $matches);

// Result - array(1) { [0]=> array(0) { } }
$pattern = '/\$[\d]+\.?[\d]{0,2}/';
preg_match($pattern, "text $50 more 234", $matches);

// Result - array(1) { [0]=> array(1) { [0]=> string(3) "$50" } }

Apparently, when you want to use regex as a pattern in preg_match() or preg_match_all(), the regex pattern needs to be placed inside single quotes and not double quotes.

You learn something new everyday.

Leave your comment

Required.

Required. Not published.

If you have one.