The /x modifier will ignore whitespaces and allow for comments. I think php.net is awesome, but in the area of PCRE it is certainly lacking. The examples are sparse if present at all.
You could do a php info to see which version of PCRE your server is running, but that is not your problem here. Older versions may have bugs, but from what I have seen the bugs would only be visible under some very unusual expressions.
Anyway, lets look at several examples so as to give an idea about what PCRE is doing.
/i means that it is case insensitive.
/x means that you can use whitespace and comments in your PCRE. This is fine if you are going to have some very complicated PCRE and need to annotate your PCRE for later reference or for others to be able to read it.
Starting with your PCRE
Code:
<?php
$patterns = array();
$replacements = array();
$input = "5 x 105";
$patterns[] = '/(\d) x 10(\d)/ix';
$replacements[] = '$1 x 10<sup>$2</sup>';
$contents = preg_replace($patterns, $replacements, $input);
echo "$contents";
?>
Your script matches 5x105, not If you want it to match 5 x 105 you will need to use:
Code:
<?php
$patterns = array();
$replacements = array();
$input = "5 x 104";
$patterns[] = '/(\d)\s x \s10(\d)/ix';
$replacements[] = '$1 x 10<sup>$2</sup>';
$contents = preg_replace($patterns, $replacements, $input);
echo "$contents";
?>
\s will match any whitespace. This can be a space or newline, carriage return, formfeed horizontal whitespace, or tab.
When not using the /x modifier your PCRE should look like this:
Code:
<?php
$patterns = array();
$replacements = array();
$input = "5 x 104";
$patterns[] = '/(\d)\sx\s10(\d)/i';
$replacements[] = '$1 x 10<sup>$2</sup>';
$contents = preg_replace($patterns, $replacements, $input);
echo "$contents";
?>
or
Code:
<?php
$patterns = array();
$replacements = array();
$input = "5 x 104";
$patterns[] = '/(\d) x 10(\d)/i';
$replacements[] = '$1 x 10<sup>$2</sup>';
$contents = preg_replace($patterns, $replacements, $input);
echo "$contents";
?>
If you are only going to use one item in your array then you could make it simpler by using only variables as opposed to arrays, but if you plan on potentially using variable numbers of patterns and/or replacements then this is a good idea, but I have always found that to be needlessly complicated. Depends on what you need though.
Code:
<?php
$input = "5 x 104";
$patterns = '/(\d) x 10(\d)/i';
$replacements= '$1 x 10<sup>$2</sup>';
$contents = preg_replace($patterns, $replacements, $input);
echo "$contents";
?>
or
Code:
<?php
$input = "5 x 104";
$contents = preg_replace('/(\d) x 10(\d)/i', '$1 x 10<sup>$2</sup>', $input);
echo "$contents";
?>
is a little simpler, but again, it all depends on what your needs are.
EDIT: I misspoke earlier. I have used the /x modifier before. I even wrote about it in one of my tutorials on PCRE
.
Bookmarks