Tuesday, July 16, 2013

php preg_replace

Example # Using backreferences followed by numeric literals
<?php
$string 
'April 15, 2003';$pattern '/(\w+) (\d+), (\d+)/i';

$replacement '${1}1,$3';
echo 
preg_replace($pattern$replacement$string);?>
The above example will output:
April1,200

Example # Using indexed arrays with preg_replace()
<?php
$string 
'The quick brown fox jumped over the lazy dog.'; 

$patterns = array(); 
$patterns[0] = '/quick/';
$patterns[1] = '/brown/'; 
$patterns[2] = '/fox/'; 
$replacements = array();
$replacements[2] = 'bear'; 
$replacements[1] = 'black'; 
$replacements[0] = 'slow';
echo 
preg_replace($patterns$replacements$string);?>
The above example will output:
The bear black slow jumped over the lazy dog.

Example # Strip whitespace
This example strips excess whitespace from a string.
<?php
$str 
'foo   o';$str preg_replace('/\s\s+/'' '$str);// This will be 'foo o' nowecho $str;?>
Example # Using the count parameter
<?php
$count 
0;

echo 
preg_replace(array('/\d/''/\s/'), '*''xp 4 to', -$count);
echo 
$count//3?>
The above example will output:
xp***to
3

If you would like to remove a tag along with the text inside it then use the following code. 

<?php 
preg_replace
('/(<tag>.+?)+(<\/tag>)/i', '', $string); ?> 
example 
<?php $string='<span class="normalprice">55 PKR</span>'; ?> 
<?php 
$string 
= preg_replace('/(<span class="normalprice">.+?)+(<\/span>)/i', '', $string); ?> 
This will results a null or empty string. 

<?php 
$string
='My String <span class="normalprice">55 PKR</span>'; 
$string = preg_replace('/(<span class="normalprice">.+?)+(<\/span>)/i', '', $string); ?>

No comments:

Post a Comment