Trying to call a function inside preg_replace - php

$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.

Related

Not incrementing variable in an anonymous callback function

I've tried to use both preg_replace and preg_replace_callback maybe in a wrong way. What I do wrong?
$str = '/admin/companies/{company}/projects/{project}/photos/{photo}/delete';
$pattern = '/({\w+})/';
$replacement = ['str_1', 'str_2', 'str_3'];
$i = 0;
$result = preg_replace_callback($pattern, function($matches) use ($i, $replacement) {
return $replacement[$i++];
}, $str);
Current Output: /admin/companies/str_1/projects/str_1/photos/str_1/delete
Expected Output: /admin/companies/str_1/projects/str_2/photos/str_3/delete
You want to pass $i by reference, so it gets updated when you increment it with $i++:
$result = preg_replace_callback($pattern, function($matches) use (&$i, $replacement) {
return $replacement[$i++];
}, $str);
Notice the & before $i.

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.

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

How to create a function that can transform the last word into Uppercases?

How do i create a function replaceMe() in php that would turn:
$str = 'This is a very long string';
into:
'This is a very long STRING?'
can someone help me?
You apparently want to do a regular expression substitution, anchored at the end of the line. Use preg_replace:
$str = 'This is a very long string';
# This is a very long LINE
echo preg_replace("/string$/", "LINE", $str);
For a general case, you can provide a callback instead of a replacement string, and simply uppercase the matched substring with preg_replace_callback:
$str = 'This is a very long blah';
function word_to_upper($match) {
return strtoupper($match[1]);
}
# This is a very long BLAH
echo preg_replace_callback("/(\w+)$/", "word_to_upper", $str);
If you're using PHP 5.4 or greater, you can supply the callback as an anonymous function:
echo preg_replace_callback("/(\w+)$/", function ($match) {
return strtoupper($match[1])
}, $str);
This works:
$str = 'This is a very long string';
echo $str."<br/>";
function replaceMe($str = "")
{
$words = explode(" ",$str);
$totalwords = count($words)-1;
$lastword = $words[$totalwords];
$words[$totalwords] = strtoupper($lastword);
$str = implode(" ",$words);
return $str;
}
echo replaceMe($str);
?>
Output:
This is a very long string
This is a very long STRING
$str = 'This is a very long string.';
function lastWordUpper($str){
$temp = strrev($str);
$last = explode(" ", $temp, 2);
return strrev(strtoupper($last[0]). ' ' .$last[1]) ;
}
echo lastWordUpper($str);

PHP preg_quote in replacement string

I use preg_replace and I want to include a url inside the replacement string. How do I quote that string? It appears preg_quote is only for the search pattern.
$replace = '\1'.addslashes($url).'\3'.addslashes($title).'\4';
Escapes are needed
addslashes is not sufficient
preg_quote escapes too much
See this demo.
As Mario commented you can use addcslashes($str, "\\$").
Unfortunately there is no generic way to do this, but addslashes should be enough in most cases.
For maximum safety you can use the ${1} syntax. E.g.
$replace = '${1}'.addslashes($url).'${3}'.addslashes($title).'${4}';
If you really want to be totally bulletproof, use a callback replacement function with preg_replace_callback(). The string returned from the callback function is used entirely as-is, so you don't have to worry about mixing replacement syntax with normal text.
Example with preg_replace_callback():
class URLReplacer {
public $pattern = '/my regex/';
public $url;
public $title;
function __construct($url, $title) {
$this->url = $url;
$this->title = $title;
}
function _callback($matches) {
return $matches[1].$url.$matches[3].$title.$matches[4];
}
function replace($subject) {
return preg_replace_callback($this->pattern, array($this, '_callback'), $subject);
}
}
$repl = new URLReplacer($url, $title);
$replaced = $repl->replace($subject);
You did not provide an example, so I compiled one on my own. The working solution I came up with is using a simple callback function:
$url = 'http://example.com/';
$title = 'Make it Complex \4';
$subject = 'Call \\4 " $me an url';
$pattern = '/(.*)an()( )(url)/';
$replace = function($m) use ($url, $title)
{
return "$m[1]$url$m[3]$title$m[4]";
};
$result = preg_replace_callback($pattern, $replace, $subject);
Result:
Call \4 " $me http://example.com/ Make it Complex \4url
The callback function is a so called anonymous function Docs which makes it easy to edit the code in place.
In case you need this more often you can put that into a function of your own, probably to make it more re-useable. You can even go to that far and create yourself your own pattern to replace subgroup matches and variables. For examle {\1} stands for the subpattern 1 match, {$2} for the second variable. Wrapping this into a function of it's own:
$patternf = function()
{
$values = func_get_args();
$mask = $values ? array_shift($values) : NULL;
return function($matches) use ($mask, $values)
{
$parts = preg_split('/({[\\\\\\$][0-9]{1,3}})/', $mask, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
foreach($parts as &$part)
if (preg_match('/^{([\\\\\\$])([0-9]{1,3})}$/', $part, $p))
$part = $p[1] == '\\' ? $matches[(int)$p[2]] : $values[$p[2]-1];
return implode('', $parts);
};
};
Would allow you to make the replacement more handy:
$replace = $patternf('{\1}{$1}{\3}{$2}{\4}', $url, $title);
$result = preg_replace_callback($pattern, $replace, $subject);
Demo. Wrapping this into a function of it's own:
function preg_replace_subst($pattern, $replace, $subject)
{
$values = func_get_args();
$pattern = array_shift($values);
$mask = array_shift($values);
$subject = array_shift($values);
$callback = function($matches) use ($mask, $values)
{
$parts = preg_split('/({[\\\\\\$][0-9]{1,3}})/', $mask, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
foreach($parts as &$part)
if (preg_match('/^{([\\\\\\$])([0-9]{1,3})}$/', $part, $p))
$part = $p[1] == '\\' ? $matches[(int)$p[2]] : $values[$p[2]-1];
return implode('', $parts);
};
return preg_replace_callback($pattern, $callback, $subject);
}
Would give it an easy interface:
$url = 'http://example.com/';
$title = 'Make it Complex \4';
$subject = 'Call \\4 " $me an url';
$pattern = '/(.*)an()( )(url)/';
$replace = '{\1}{$1}{\3}{$2}{\4}';
$result = preg_replace_subst($pattern, $replace, $subject, $url, $title);
But with many substitution variables it should be possible to pass them as an array probably otherwise it gets a bit lengthy.
Using the e modifier with preg_replace (and why it does not work)
When using the e modifier, the matches get replaced in the replace string and it then get's evaluated. As other variables do not get escaped, the matches do interfere with PHP variable substitution, which is dangerous:
$url = 'http://example.com/';
$title = 'Make it Complex \4';
$subject = 'Call me an url.';
$pattern = '/(.*)an()( )(url)/e';
$replace = '"$1{$url}$3{$title}$4"';
$result = preg_replace($pattern, $replace, $subject);
Outputs:
Call me http://example.com/ Make it Complex \4url.
As written, the first e-modifier example is broken because $ won't get escape in $subject, so PHP would have looked for unset variables. That's dangerous, too. I came up with a variant, it solves that issue but it can't handle double-quotes in the subject:
$url = 'http://example.com/';
$title = 'Make it Complex \4';
$subject = 'Call \\4 " $me an url';
$pattern = '/(.*)an()( )(url)/e';
$replace = "'\$1'.\$url.'\$3'.\$title.'$4'";
Output:
Call \4 \" $me http://example.com/ Make it Complex \4url
^ problem, not in input.
So not really fool-proof, that's why it needs the callback function because it gets the matching sub-patterns unquoted.
To make it obvious one is escaping any potential back-references in the $replacement parameter of preg_replace(), use a function:
function preg_quote_replacement($input) {
return addcslashes($input, '\\$');
}
In OP's case:
$subject = preg_replace(
$pattern,
'\1'.preg_quote_replacement($url).'\3'.preg_quote_replacement($title).'\4',
$subject
);
You should use Prepared Patterns. It works like Prepared Statements in SQL:
Pattern::inject("\1#url\2#url\3", ['url' => $input]);

Categories