preg_replace_callback() walk around - php

Would like to do something like this:
$str = '<a>lalala</a>';
echo preg_replace('~<a>(.*)</a>~i','<a>'.str_replace('la','mi',"$1").'</a>',$str);
So it would return:
<a>mimimi</a>
But can't use preg_replace_callback() function. Any simple ideas?

You could use preg_replace_callback() to do specific operations in replacement:
$str = '<a>lalala</a>';
echo preg_replace_callback('~<a>(.*)</a>~i',function($matches){
return '<a>'.str_replace('la','mi',$matches[1]).'</a>';
},$str);
Outputs:
<a>mimimi</a>
Or with preg_match():
$str = '<a>lalala</a>';
if (preg_match('~<a>(.*)</a>~i', $str, $matches)) {
$str = '<a>'.str_replace('la','mi',$matches[1]).'</a>';
};
echo $str;

Related

Trying to call a function inside preg_replace

$string = 'Hello [user=1]';
$bbc = array('/\[user=(.*?)\]/is');
$replace = array(user('textlink',$1));
$s = preg_replace($bbc , $replace, $string);
echo $s
How do I change $1 in preg_replace with a function?
If I understand you correctly, you want to execute user() function on each match? As mentioned in comments, use the preg_replace_callback() function.
<?php
$string = 'Hello [user=1]';
$s = preg_replace_callback(
'/\[user=(.*?)\]/is',
function($m) {return user('textlink', $m[1]);},
$string
);
echo $s;
You may use a preg_replace_callback_array:
$string = 'Hello [user=1]';
$bbc = array(
'/\[user=(.*?)\]/is' => function ($m) {
return user('textlink',$m[1]);
});
$s = preg_replace_callback_array($bbc, $string);
echo $s;
See PHP demo.
You may add up the patterns and callbacks to $bbc.

php extract a sub-string before and after a character from a string

need to extract an info from a string which strats at 'type-' and ends at '-id'
IDlocationTagID-type-area-id-492
here is the string, so I need to extract values : area and 492 from the string :
After 'type-' and before '-id' and after 'id-'
You can use the preg_match:
For example:
preg_match("/type-(.\w+)-id-(.\d+)/", $input_line, $output_array);
To check, you may need the service:
http://www.phpliveregex.com/
P.S. If the function preg_match will be too heavy, there is an alternative solution:
$str = 'IDlocationTagID-type-area-id-492';
$itr = new ArrayIterator(explode('-', $str));
foreach($itr as $key => $value) {
if($value === 'type') {
$itr->next();
var_dump($itr->current());
}
if($value === 'id') {
$itr->next();
var_dump($itr->current());
}
}
This is what you want using two explode.
$str = 'IDlocationTagID-type-area-id-492';
echo explode("-id", explode("type-", $str)[1])[0]; //area
echo trim(explode("-id", explode("type-", $str)[1])[1], '-'); //492
Little Simple ways.
echo explode("type-", explode("-id-", $str)[0])[1]; // area
echo explode("-id-", $str)[1]; // 492
Using Regular Expression:
preg_match("/type-(.*)-id-(.*)/", $str, $output_array);
print_r($output_array);
echo $area = $output_array[1]; // area
echo $fnt = $output_array[2]; // 492
You can use explode to get the values:
$a = "IDlocationTagID-type-area-id-492";
$data = explode("-",$a);
echo "Area ".$data[2]." Id ".$data[4];
$matches = null;
$returnValue = preg_match('/type-(.*?)-id/', $yourString, $matches);
echo($matches[1]);

Using preg_replace to get $_GET variables

I made the following PHP function:
<?php
function convertGET($str) {
$regex = '/GET:+([a-zA-Z0-9_]+)/';
$str = preg_replace($regex, $_GET["$1"], $str);
return($str);
}
$string = "foobar: GET:foobar";
$string = convertGET($string);
echo $string;
?>
The function is suppost to get a string and replace something like:
GET:foobarwith the $_GET variable "foobar".
Use preg_replace_callback() instead:
<?php
$input = array("foobar" => "Some other string");
$regex = '~GET:([a-zA-Z0-9_]+)~';
$string = "foobar: GET:foobar";
$string = preg_replace_callback($regex,
function($matches) use ($input) {
return $input[$matches[1]];
},
$string);
echo $string;
// output: foobar: Some other string
?>
See a demo on ideone.com.

Extract url from string via preg match in php

$str = 'window.location.href="http://my-site.com";'
I want to extract the url from $str. I am not that good in preg_match(). However with the following code:
preg_match('/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/', $str, $link);
if (empty($link[0])) {
echo "Nothing found!";
} else {
echo $link[0];
}
I am able to get the result http://my-site.com";. I want to customize preg_match() to exclude "; from the result. Please help!
<?php
$str = 'window.location.href="http://my-site.com";';
preg_match('/window\.location\.href="(.*?)";/', $str, $result);
echo $result[1];
//http://my-site.com
>?
http://ideone.com/YTk70i
If you dont feel comfortable with preg_* then try keeping it simple. It seems a bit of an unnecessary overhead loading the regex engine anyway for something that simple.
Try this instead :-
$str = 'window.location.href="http://my-site.com";';
$p1 = strpos($str, 'href="') + strlen('href="');
$p2 = strpos($str, '";', $p1);
$url = substr($str,$p1,$p2-$p1);
echo $p1 .PHP_EOL;
echo $p2 .PHP_EOL;
echo $url;
This yeilds the following
22
40
http://my-site.com
i.e everything between href=" and ";
Try this:
preg_match('/^window.location.href="([^"]+)";$/', $str, $link);

How to find a string in a variable using PHP and regular expressions

I am trying to find the word and add a number next to it. How could he do? I tried with the code below, but I could not. Could anyone help me?
Thank you!
$string = 'I220ABCD I220ABCDEF I220ABCDEFG'
if (preg_match("/I220.*/", $string, $matches)) {
echo $matches[0];
}
Expected result:
I220ABCD9
I220ABCDEF10
I220ABCDEFG11
Use preg_replace_callback instead like this:
$str = 'I220AB FRRRR CD I221ABCDEF I220AB DSFDSF CDEFG';
$repl= preg_replace_callback('~(I220[^\s]+)~', function($m) {
static $i=9;
return $m[1] . $i++;
}, $str);
echo $repl\n"; // I220AB9 FRRRR CD I221ABCDEF I220AB10 DSFDSF CDEFG
I dont know what your requirnments for adding the number at the end are so i just incremeneted during the loop;
$string = 'I220ABCD I220ABCDEF I220ABCDEFG';
$arrayStrings = explode(" ", $string);
$int = 9;
$newString = '';
foreach($arrayStrings as $stringItem)
{
if (preg_match("/I220.*/", $stringItem, $matches))
{
$stringItem = $stringItem.$int;
$newString = $newString.$stringItem." ";
$int++;
}
}
echo $newString;
Use preg_replace_callback():
$string = 'I220ABCD I220ABCDEF I220ABCDEFG';
// This requires PHP5.3+ since it's using an anonymous function
$result = preg_replace_callback('/I220[^\s]*/', function($match){
return($match[0].rand(0,10000)); // Add a random number between 0-10000
}, $string);
echo $result; // I220ABCD3863 I220ABCDEF5640 I220ABCDEFG989
Online demo.
You'll need to use a catch block in your regex e.g. "/I220([^ ]+)/" and if you want them all, you'll need to use preg_match_all, too.
preg_replace_callback with your needs:
$string = 'I220ABCD I220ABCDEF I220ABCDEFG';
class MyClass{
private static $i = 9;
private static function callback($matches){
return $matches[0] . self::$i++;
}
public static function replaceString($string){
return preg_replace_callback('/I220[^\s]+/',"self::callback",$string);
}
}
echo(MyClass::replaceString($string));
of course you can edit to class to initialize the way you want

Categories