I have this code:
<?php
$array = array();
$test = 'this is a #test';
$regex = "#(\#.+)#";
$test = preg_replace($regex, '<strong>$1</strong>', $test);
echo $test;
?>
and I would like to do: $array[] = $1
Does anyone have a suggestion, please?
If you use PHP ≥ 5.3.0 you can use an anonymous function and preg_replace_callback. First the callback:
$array = array();
$callback = function ($match) use (&$array) {
$array[] = $match[1];
return '<strong>'.$match[1].'</strong>';
};
$input = 'this is a #test';
$regex = '/(#.*)/';
$output = preg_replace_callback($regex, $callback, $input);
echo "Result string:\n", $output, "\n";
echo "Result array:\n";
print_r($array);
Results in:
Result string:
this is a <strong>#test</strong>
Result array:
Array
(
[0] => #test
)
Before PHP 5.3.0 you can only use create_function or any function defined somewhere else in the code. Both of them cannot access the local variable $array defined in the parent scope of $callback. In this case you would either have to use a global variable for $array (ugh!) or define the function inside a class and make $array a member of that class.
In PHP 4 >= 4.0.5, PHP 5, use preg_replace_callback with global variable.
PHP code:
$array = array();
$input = 'this is a #test';
$regex = '/(#\w*)/';
$output = preg_replace_callback(
$regex,
create_function(
'$match', 'global $array;
$array[] = $match[1]; return "<strong>" . $match[1] . "</strong>";'),
$input);
echo "Result string:\n", $output, "\n\n";
echo "Result array:\n";
print_r($array);
Output:
Result string:
this is a <strong>#test</strong>
Result array:
Array
(
[0] => #test
)
Demo:
Click here.
You can use:
preg_match($regex, $test, $matches);
$my_array = $matches[1];
Related
this is my code
<?php
$string = 'this
this
good
good
hahah';
$rows = explode("\n",$string);
$unwanted = 'this|good';
$cleanArray= preg_grep("/$unwanted/i",$rows,PREG_GREP_INVERT);
$cleanString=implode("\n",$cleanArray);
print_r ( $cleanString );
?>
display
hahah
i want like this
this
good
hahah
i want to keep one...
please help me, thanks guys
This code resorts to checking each line to see if it matches your $unwanted string, but it also creates an array of strings it has already encountered so it checks if it has previously been encountered ( using in_array()). If it matches and has been encountered before it uses unset() in the original $rows to remove the line...
$string = 'this
this
good
good
hahah';
$rows = explode("\n",$string);
$unwanted = 'this|good';
$matched = [];
foreach ( $rows as $line => $row ) {
if ( preg_match("/$unwanted/i",$row, $matches)) {
if ( in_array(trim($matches[0]), $matched) === true ) {
unset($rows[$line]);
}
$matched[] = $matches[0];
}
}
$cleanString=implode("\n",$rows);
print_r ( $cleanString );
<?php
$string = 'this
this
good
yyyy
good
xxxx
hahah';
print_r(
implode("\n",
array_diff(array_unique(
array_map(function($v) { return trim($v);}, explode("\n",$string))
)
,array('xxxx', 'yyyy')))
);
?>
output:
this
good
hahah
Refer: https://ideone.com/Eo0MIM
You can use this simple code to get result:
$result = array_unique(explode("\n",str_replace(" ", "", $string)));
print_r ($result);
If you want more control over your data, use this code
$rows = explode("\n", $string);
$words = [];
foreach($rows as $row) {
$row = trim($row);
$words[$row] = true;
}
foreach($words as $word => $tmp) {
echo $word . "\n";
}
Here is one way you could do this:
$string = 'this
this
good
good
hahah';
preg_match_all('/([a-z])+/', $string, $matches);
$string = implode("\n",array_unique($matches[0]));
echo $string;
You can use php inbuilt array_unique function
<?php
$string = 'this
this
good
good
haha';
$rows = explode("\n",$string);
$cleanArray = array_unique($rows);
$cleanString=implode("\n",$cleanArray);
print_r ( $cleanString );
//result is this good haha
$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.
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.
I have this string
$s = 'Yo be [diggin = array("fruit"=> "apple")] scriptzors!';
which then gets checked by
$matches = null;
preg_match_all('/\[(.*?)\]/', $s, $matches);
var_dump($matches[1]);
but what I want it to do is the following, it should return the following
print "yo be";
$this->diggin(SEND ARRAY HERE);
print "scriptzors!";
EDIT to show issue with below answer
$s = 'Yo be [diggin = array("fruit"=>"apple")] scriptzors!';
$matches = null;
preg_match_all('/\[(.*?)\]/', $s, $matches);
$var = explode(' = ', $matches[1]);
print $var[0]; //THIS DOES NOT PRINT
You're sort of close. You can explode the string with = but with spaces included around the =. Then the first element would be the function name, in this case diggin and the second element would be the array but as a string. You'll need to eval that one so that it'll be a proper array data type.
$var = explode(' = ', $matches[1][0]);
call_user_func_array(array($this, $var[0]), eval($var[1] . ';'));
// or do
$this->{var[0]}(eval($val[1] . ';'));
As an alternative, you can also modify the regex so that you don't have to call explode.
preg_match_all('/\[([a-z0-9_]*)\s*?=\s*(.*)\]/i', $s, $matches);
Either way, you'll want to make sure that you sanitize the user input because eval can be evil.
This will call the function without using eval and exposing yourself to code injection.
preg_match_all('/\[([a-z0-9_]*)\s*?=\s*array\((.*)*\)\]/i', $s, $matches);
$var = explode(',', $matches[2][0]);
$result = array();
foreach ($var as $value) {
$keyvaluepair = explode('=>', $value);
$result[$keyvaluepair[0]] = $keyvaluepair[1];
}
$this->{var[0]}($result);
Could you tell how to replace string by preg-replace (need regular expression):
/user/{parent_id}/{action}/step/1
At the equivalent values of an array:
array('parent_id'=>32, 'action'=>'some');
To make:
/user/32/some/step/1
Addition
This is a typical problem, so I probably will not know what the names of variables come
You can use str_replace
For example:
str_replace(array("{parent_id}", "{action}"), array(32, 'some'), "/user/{parent_id}/{action}/step/1");
$arr = array('parent_id'=>32, 'action'=>'some');
$out = str_replace(array_keys($arr),array_values($arr),$in);
no need for regexps!
Say you have:
$arr = array('parent_id'=>32, 'action'=>'some');
$in = '/usr/{parent_id}/{action}/step/1';
This will replace the braces:
function bracelize($str) {
return '{' . $str . '}';
}
$search = array_map('bracelize', array_keys($arr));
$out = str_replace($search, $arr, $in);
Or if you are using PHP >= 5.3 you can use lambdas:
$search = array_map(function ($v) { return '{'.$v.'}';}, array_keys($arr));
$out = str_replace($search, $arr, $in);
$s = '/user/{parent_id}/{action}/step/1';
$replacement = array('parent_id'=>32, 'action'=>'some');
$res = preg_replace(array('/\\{parent_id\\}/', '/\\{action\\}/'), $replacement, $s);
Of course, you could just as well use str_replace (in fact, you ought to).
<?php
$string = '/usr/{parent_id}/{action}/step/1';
$pattern = array('#{parent_id}#', '#{action}#');
$values = array('32', 'some');
echo preg_replace($pattern, $values, $string);
?>
If your problem is not more complicated than this, i would recommend changing preg_replace to str_replace though.
EDIT: I see you don't know the variable names in advance. In which case you could do something like this.
<?php
function wrap_in_brackets(&$item)
{
$item = '{' . $item . '}';
return true;
}
$string = '/usr/{parent_id}/{action}/step/1';
$variables = array('parent_id' => 32, 'action' => 'some');
$keys = array_keys($variables);
array_walk($keys, 'wrap_in_brackets');
echo str_replace($keys, array_values($variables), $string);
?>
Expanding on mvds' answer:
$in = 'user/{parent_id}/{action}/step/1';
$arr = array('{parent_id}' => 32, '{action}' => 'some');
$out = str_replace(array_keys($arr), $arr, $in);
Or:
$in = 'user/{parent_id}/{action}/step/1';
$arr = array('parent_id' => 32, 'action' => 'some');
$arr[] = '';
$find = array_merge(array_keys($arr), array('{', '}'));
$out = str_replace($find, $arr, $in);