I have the following preg_replace not preg_replace_callback which uses arrays for search patterns and replacement not only a single value and it works fine:
preg_replace(['/\{/','/\}/','/"(.*?)"/'],['<span class=\'olive\'>{','}</span>','<span class=\'olive\'>${0}</span>'],FoxText::insertBr($model->TafseerText));
However, when I try to pass ${0} to function something like:
preg_replace(['/\{/','/\}/','/"(.*?)"/'],['<span class=\'olive\'>{','}</span>',FoxText::pattern2VerseId("\$0")],FoxText::insertBr($model->TafseerText));
In the FoxText::pattern2VerseId function I try print_r as follows:
public static function pattern2VerseId($txt, $pattern = '/\(((\d+)-(\w+))\)/u')
{
$parts = array_map('trim',explode('-', $txt));
print_r(explode('-', $parts[0]));
return $parts[0].' *'.$parts[0].'|';
}
It prints Array ( [0] => $0 ) while the return value is matched string from the previous call!
In other words, how could it able to return $parts[0] as a string and It could not able to explode this string. Or how could I pass the value correctly to the function to be processed there?
By the way, the string is something like (125-Verse)
Because when you call the function pattern2VerseId you call it with the string $0. And since string $0 doesn't contain any hyphen, the explode just returns an array with single element containing the string.
explode('-', '$0') // will return Array([0] => $0)
By "\$0" are you actually trying to get the first part of the matched regex, i.e. 125 in this case? Because you're not doing it right.
Since I have PHP < 7. i.e there is no preg_replace_callback_array, the only solution that I have able to use is replacing the first pattern(s) using preg_replace then passing the output to one preg_replace_callback
$p = preg_replace(['/\{/','/«/','/\(/','/\}/','/»/','/\)/','/"(.*?)"/'],['<span class=\'olive\'>{','<span class=\'olive\'>«','<span class=\'olive\'>(','}</span>','»</span>',')</span>','<span class=\'olive\'>${0}</span>'],FoxText::insertBr($model->TafseerText));
$callback = function($m){return FoxText::pattern2VerseId($m);};
echo preg_replace_callback('/\(((\d+)-(\w+))\)/u', $callback, $p);
Related
I Need PHP Function that can get the most letters from the string
$string = "111010111010001101";
$execute = SomeFunction($string);
echo $execute;
and the ouput will be like this
1
is there a php function like that? Thank you
Here you go
$string = "111010111010001101";
//$string = "abaacabdeeeee";
$array_count = array_count_values(str_split($string));
$res = array_keys($array_count, max($array_count));
print_r($res);
To make it a function, just do this:
function SomeFunction($string){
$array_count = array_count_values(str_split($string));
return array_keys($array_count, max($array_count));
}
print_r(SomeFunction('111010111010001101'));
Output
1 //or e in the commented one I tested
Sandbox
How it works:
Split the string into an array of chars str_split
count the occurrences of the chars array_count_values
get the key with the max number of occurrences array_keys and max
Caveats:
If two values are equal then they will both be returned in the result. For example
$string = 'ababababcd';
Output
Array
(
[0] => a
[1] => b
)
You never mentioned what you want to happen in this case (a tie). For your particular case that may not even be an issue. But I had to mention it for the sake of completeness. If you don't want the return as an array you can do something like this (to return false or the first element):
function SomeFunction($string){
$array_count = array_count_values(str_split($string));
$res = array_keys($array_count, max($array_count));
if(empty($res)) return false;
return array_shift($res);
}
Cheers!
Not effective but simple
max(str_split($string));
Yes, so long as your character set isn't a multibyte one with multibyte characters in the string. See the manual page for count_chars
My code:
$q = array('r%and_dy', 'cat09', '##$%%^');
$result = preg_grep('/[a-zA-Z0-9]+/', $q);
print_r($result);
Using the same regular expression with javascript will only match 'cat09', but in php this returns:
Array
(
[0] => r%and_dy
[1] => cat09
)
What do I have to write so that it only returns 'cat09'?
EDIT: you want to see the javascript. The javascript match function with the 'g' flag is the equivalent function of preg_grep in php, but it doesn't accept an array - here's a fiddle, which each item as a separate line. http://jsfiddle.net/64A5w/
EDIT: jsfiddle is down, so here is the the javascript equivalent. First I should mention, preg_grep only accepts arrays, and automatically returns global matches (it does not accept a g flag). Javascript match only accepts strings, and g must be specified.
var str = 'r%and_dy';
var result = str.match(/[a-zA-Z0-9]+/g);
document.write(result);
which displays: r,and,dy. The php equivalent would be passing preg_grep $str = array('r%and_dy'). It should return the same array But it returns r%and_dy as a single match (as shown above).
Your problem is that you are matching strings that contain one or more alphanumeric character. Try:
$q = array('r%and_dy', 'cat09', '##$%%^');
$result = preg_grep('/^[a-zA-Z0-9]+$/', $q);
print_r($result);
The ^ and $ mean the start and the end of the string respectively.
From the manual:
Returns the array consisting of the elements of the input array that match the given pattern.
I want to replace all strings in square brackets ([]) with a randomly chosen item from an array that's named that string.
It's very similar to this issue, but with a twist, in that I want to replace different brackets' contents with strings from arrays named that.
An example should make this a bit clearer.
So say I've got the string
"This is a very [adjective] [noun], and this is a [adjective] [noun]."
And the variables:
$adjective = array("big","small","good","bad");
$noun = array("house","dog","car");
And we want it to return "This is a very big house, and this is a good dog." or whatever, by choosing randomly. That is, I want to write a PHP function that will replace each [string] with a randomly chosen item from the array named $string. For now it doesn't matter if by randomly choosing it ends up repeating choices, but it must make a fresh choice for each [] item.
I hope I've explained this clearly. If you get what I'm trying to achieve and can think of a better way to do it I'd be very grateful.
Algorithm
Match for this regex: (\[.*?\])
For each match group pick an item from the related array.
Replace in string by order.
Implementation
$string = "This is a very [adjective] [noun], and this is a [adjective] [noun].";
$adjective = array("big","small","good","bad");
$noun = array("house","dog","car");
// find matches against the regex and replaces them the callback function.
$result = preg_replace_callback(
// Matches parts to be replaced: '[adjective]', '[noun]'
'/(\[.*?\])/',
// Callback function. Use 'use()' or define arrays as 'global'
function($matches) use ($adjective, $noun) {
// Remove square brackets from the match
// then use it as variable name
$array = ${trim($matches[1],"[]")};
// Pick an item from the related array whichever.
return $array[array_rand($array)];
},
// Input string to search in.
$string
);
print $result;
Explanation
preg_replace_callback function performs a regular expression search and replace using provided callback function.
First parameter is regular expression to match (enclosed between slashes): /(\[.*?\])/
Second parameter is callback function to call for each match. Takes the current match as parameter.
We have to use use() here to access the arrays from inside the function, or define the arrays as global: global $adjective = .... Namely, we have to do one of the followings:
a) Define arrays as global:
...
global $adjective = array("big","small","good","bad");
global $noun = array("house","dog","car");
...
function($matches) {
...
b) Use use:
...
$adjective = array("big","small","good","bad");
$noun = array("house","dog","car");
...
function($matches) use ($adjective, $noun) {
...
First line of the callback function:
trim: Removes square brackets ([]) from the match using trim function.
${}: Creates a variable to use as array name with the match name. For example, if the $match is [noun] then trim($matches[1],"[]") returns noun (without brackets) and ${noun} becomes the array name: $noun. For more information on the topic, see variable variables.
Second line randomly picks an index number available for the $array and then returns the element at this position.
Third parameter is the input string.
The code below will do the work:
$string = "This is a very [adjective] [noun], and this is a [adjective] [noun]."
function replace_word ( $matches )
{
$replaces = array(
'[adjective]' => array("big", "small", "good", "bad"),
'[noun]' => array("house", "dog", "car")
);
return $replaces[$matches[0]][array_rand($replaces[ $matches[0] ])];
}
echo preg_replace_callback("(\[.*?\])", "replace_word", $string);
First, we regular expression match on the [something] parts of the word, and call the replace_word() callback function on it with preg_replace_callback(). This function has an internal $replaces two dimension deep array defined inside, each row defined in a [word type] => array('rep1', 'rep2', ...) format.
The tricky and a bit obfuscated line is the return $replaces[$matches[0]][array_rand($replaces[ $matches[0] ])];. If I chunk it down a bit, it'll be a lot more parsable for you:
$random = array_rand( $replaces[ $matches[0] ] );
$matches[0] is the word type, this is the key in the $replaces array we are searching for. This was found by regular expression in the original string. array_rand() basically selects one element of the array, and returns its numerical index. So $random right now is an integer somewhere between 0 and the (number of elements - 1) of the array containing the replaces.
return $replaces[ $matches[0] ][$random];
This will return the $randomth element from the replace array. In the code snippet, these two lines are put together into one line.
Showing one element only once
If you want disjunct elements (no two adjective or noun repeated twice), then you will need to do another trick. We will set the $replaces array to be defined not inside the replace_word() function, but outside it.
$GLOBALS['replaces'] = array(
'[adjective]' => array("big", "small", "good", "bad"),
'[noun]' => array("house", "dog", "car")
);
Inside the function, we will set the local $replaces variable to be a reference to the newly set array, with calling $replaces = &$GLOBALS['replaces'];. (The & operator sets it a reference, so everything we do with $replaces (remove and add elements, for example) modifies the original array too. Without it, it would only be a copy.)
And before arriving on the return line, we call unset() on the currently to-be-returned key.
unset($replaces[$matches[0]][array_rand($replaces[ $matches[0] ])]);
The function put together now looks like this:
function replace_word ( $matches )
{
$replaces = &$GLOBALS['replaces'];
unset($replaces[$matches[0]][array_rand($replaces[ $matches[0] ])]);
return $replaces[$matches[0]][array_rand($replaces[ $matches[0] ])];
}
And because $replaces is a reference to the global, the unset() updates the original array too. The next calling of replace_word() will not find the same replace again.
Be careful with the size of the array!
Strings containing more replace variables than the amount of replace values present will throw an Undefined index E_NOTICE. The following string won't work:
$string = "This is a very [adjective] [noun], and this is a [adjective] [noun]. This is also an [adjective] [noun] with an [adjective] [noun].";
One of the outputs look like the following, showing that we ran out of possible replaces:
This is a very big house, and this is a big house. This is also an small with an .
Another good (easier) method of doing this (not my solution)
https://stackoverflow.com/a/15773754/2183699
Using a foreach to check on which variables you want to replace and replacing them with
str_replace();
You can use preg_match and str_replace function to achive this goal.
First find the matches using preg_match function and then create search & replace array from the result.
Call str_replace function by passing the previous arrays as parameters.
This is my minor update to mmdemirbas' answer above. It lets you set the variables outside of the function (i.e. use globals, as said).
$result = preg_replace_callback(
// Matches parts to be replaced: '[adjective]', '[noun]'
'/(\[.*?\])/',
// Callback function. Use 'use()' or define arrays as 'global'
function($matches) use ($adjective, $noun) {
// Remove square brackets from the match
// then use it as variable name
$arrayname = trim($matches[1],"[]");
$array = $GLOBALS[$arrayname];
// Pick an item from the related array whichever.
return $array[array_rand($array)];
},
// Input string to search in.
$string
);
print $result;
I have this string:
a:3:{i:0;i:2;i:1;i:3;i:2;i:4;}
I want to get number between "a:" and ":{" that is "3".
I try to user substr and strpos but no success.
I'm newbie in regex , write this :
preg_match('/a:(.+?):{/', $v);
But its return me 1.
Thanks for any tips.
preg_match returns the number of matches, in your case 1 match.
To get the matches themselves, use the third parameter:
$matches = array();
preg_match(/'a:(\d+?):{/', $v, $matches);
That said, I think the string looks like a serialized array which you could deserialize with unserialize and then use count on the actual array (i.e. $a = count(unserialize($v));). Be careful with userprovided serialized strings though …
If you know that a: is always at the beginning of the string, the easiest way is:
$array = explode( ':', $string, 3 );
$number = $array[1];
You can use sscanfDocs to obtain the number from the string:
# Input:
$str = 'a:3:{i:0;i:2;i:1;i:3;i:2;i:4;}';
# Code:
sscanf($str, 'a:%d:', $number);
# Output:
echo $number; # 3
This is often more simple than using preg_match when you'd like to obtain a specific value from a string that follows a pattern.
preg_match() returns the number of times it finds a match, that's why. you need to add a third param. $matches in which it will store the matches.
You were not too far away with strpos() and substr()
$pos_start = strpos($str,'a:')+2;
$pos_end = strpos($str,':{')-2;
$result = substr($str,$pos_start,$pos_end);
preg_match only checks for appearance, it doesn't return any string.
How can I replace a certain part of my string with another one?
Input string:
"Hello, my name is Santa"
How can I change all a's in my string with something else?
I think I need a foreach loop, but I'm unsure how to use it.
strtr ($str, array ('a' => '<replacement>'));
Or to answer your question more precisely:
strtr ("Hello, my name is Santa", array ('a' => '<replacement>'));
Search & Replace
There are a few different functions/methods to replace a certain part of a string with something else, all with their own advantages.
##str_replace() method (binary safe; case-sensitive)
Arguments
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
str_replace() has 3 required arguments as you can see in the above definition with the correct order, all of which can take a string as also an array as argument!
Search & Replace
search(string) AND replace(string) → Replaces the search string with the replace string.
search(array) AND replace(string) → Replaces all search elements with the replace string.
search(string) AND replace(array) → Throws you a notice: "Notice: Array to string conversion", because a replacement array for just one search string doesn't make sense, so it tries to convert the array to a string.
search(array) AND replace(array) → Replaces each search element with the corresponding replace element (Keys are ignored!).
search(more elements) AND replace(less elements) → Replaces each search element with the corresponding replace element (For the missing replace elements an empty string will be used).
search(less elements) AND replace(more elements) → Replaces each search element with the corresponding replace element (Unneeded replace elements are ignored).
Subject
subject(string) → Replacement is done for the subject string.
subject(array) → Replacement is done for each array element.
Code
echo str_replace("search", "replace", "text search text");
echo str_replace(["t", "a"], "X", "text search text");
echo str_replace("search", ["replace1", "replace2"], "text search text");
echo str_replace(["a", "c"], ["X", "Y"], "text search text");
Output
text replace text
XexX seXrch XexX
Notice: Array to string conversion
text seXrYh text
Notes
Gotcha!
Important to know is that str_replace() works from left to right of the array. This means it can possible replace a value which you already replaced. For example:
echo str_replace(array("a", "b"), array("b", "c"), "aabb");
//Probably expected output: bbcc
//Actual output: cccc
Case insensitive
If you want to make the search case insensitive you can use str_ireplace() (Notice the i for case-insensitive).
Multidimensional array
str_replace()/str_ireplace() does NOT work for multidimensional arrays. See this manual comment for such an implementation. Of course you can also replace str_replace() with str_ireplace() for case-insensitive.
If you want to put everything together and create a function that also works for multidimensional arrays case-insensitive you can do something like this:
<?php
function str_ireplace_deep($search, $replace, $subject)
{
if (is_array($subject))
{
foreach($subject as &$oneSubject)
$oneSubject = str_ireplace_deep($search, $replace, $oneSubject);
unset($oneSubject);
return $subject;
} else {
return str_ireplace($search, $replace, $subject);
}
}
?>
##strtr() method (50% binary safe; case-sensitive)
Arguments
string strtr ( string $str , string $from , string $to )
string strtr ( string $str , array $replace_pairs )
The function either takes 3 arguments with a from and to string or it takes 2 arguments with a replacement array array("search" => "replace" /* , ... */), all of which you can see in the above definition with the correct order.
2 Arguments
It starts to replace the longest key with the corresponding value and does this until it replaced all key => value pairs. In this case the function is binary safe, since it uses the entire key/value.
3 Arguments
It replaces the from argument with the to argument in the subject byte by byte. So it is not binary safe!
If the from and to arguments are of unequal length the replacement will stop when it reaches the end of the shorter string.
Subject
It doesn't accept an array as subject, just a string.
Code
echo strtr("text search text", "ax", "XY");;
echo strtr("text search text", ["search" => "replace"]);
Output
teYt seXrch teYt
text replace text
Notes
Gotcha!
Opposed to str_replace(), strtr() does NOT replace replaced strings. As an example:
echo strtr("aabb", ["a" => "b", "b" => "c"]);
//If expecting to replace replacements: cccc
//Actual output: bbcc
Also if you want to replace multiple things with the same string you can use array_fill_keys() to fill up your replacement array with the value.
Case insensitive
strtr() is NOT case-insensitive NOR is there a case-insensitive equivalent function. See this manual comment for a case-insensitive implementation.
Multidimensional array
strtr() does opposed to str_replace() NOT work with arrays as subject, so it also does NOT work with multidimensional arrays. You can of course use the code above from str_replace() for multidimensional arrays and just use it with strtr() or the implementation of stritr().
If you want to put everything together and create a function that also works for multidimensional arrays case-insensitive you can do something like this:
<?php
if(!function_exists("stritr")){
function stritr($string, $one = NULL, $two = NULL){
/*
stritr - case insensitive version of strtr
Author: Alexander Peev
Posted in PHP.NET
*/
if( is_string( $one ) ){
$two = strval( $two );
$one = substr( $one, 0, min( strlen($one), strlen($two) ) );
$two = substr( $two, 0, min( strlen($one), strlen($two) ) );
$product = strtr( $string, ( strtoupper($one) . strtolower($one) ), ( $two . $two ) );
return $product;
}
else if( is_array( $one ) ){
$pos1 = 0;
$product = $string;
while( count( $one ) > 0 ){
$positions = array();
foreach( $one as $from => $to ){
if( ( $pos2 = stripos( $product, $from, $pos1 ) ) === FALSE ){
unset( $one[ $from ] );
}
else{
$positions[ $from ] = $pos2;
}
}
if( count( $one ) <= 0 )break;
$winner = min( $positions );
$key = array_search( $winner, $positions );
$product = ( substr( $product, 0, $winner ) . $one[$key] . substr( $product, ( $winner + strlen($key) ) ) );
$pos1 = ( $winner + strlen( $one[$key] ) );
}
return $product;
}
else{
return $string;
}
}/* endfunction stritr */
}/* endfunction exists stritr */
function stritr_deep($string, $one = NULL, $two = NULL){
if (is_array($string))
{
foreach($string as &$oneSubject)
$oneSubject = stritr($string, $one, $two);
unset($oneSubject);
return $string;
} else {
return stritr($string, $one, $two);
}
}
?>
##preg_replace() method (binary safe; case-sensitive)
Arguments
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
preg_replace() has 3 required parameters in the order shown above. Now all 3 of them can take a string as also an array as argument!
Search & Replace
search(string) AND replace(string) → Replaces all matches of the search regex with the replace string.
search(array) AND replace(string) → Replaces all matches of each search regex with the replace string.
search(string) AND replace(array) → Throws you a warning: "Warning: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array", because a replacement array for just one search regex doesn't make sense.
search(array) AND replace(array) → Replaces all matches of each search regex with the corresponding replace element(Keys are ignored!).
search(more elements) AND replace(less elements) → Replaces all matches of each search regex with the corresponding replace element(For the missing replace elements an empty string will be used).
search(less elements) AND replace(more elements) → Replaces all matches of each search regex with the corresponding replace element(Unneeded replace elements are ignored).
Subject
subject(string) → Replacement is done for the subject string.
subject(array) → Replacement is done for each array element.
Please note again: The search must be a regular expression! This means it needs delimiters and special characters need to be escaped.
Code
echo preg_replace("/search/", "replace", "text search text");
echo preg_replace(["/t/", "/a/"], "X", "text search text");
echo preg_replace("/search/", ["replace1", "replace2"], "text search text");
echo preg_replace(["a", "c"], ["X", "Y"], "text search text");
Output
text replace text
XexX seXrch XexX
Warning: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
text seXrYh text
Notes
Gotcha!
Same as str_replace(), preg_replace() works from left to right of the array. This means it can possible replace a value which you already replaced. For example:
echo preg_replace(["/a/", "/b/"], ["b", "c"], "aabb");
//Probably expected output: bbcc
//Actual output: cccc
Case insensitive
Since the search argument is a regular expression you can simply pass the flag i for case-insensitive search.
Multidimensional array
preg_replace() does NOT work for multidimensional arrays.
Backreference
Be aware that you can use \\n/$n as backreference to your capturing groups of the regex. Where 0 is the entire match and 1-99 for your capturing groups.
Also if the backreference is immediately followed by a number you have to use \${n}.
Replacement / "The /e modifier is deprecated"
The replacement in preg_replace() can't use callback functions as replacements. So you have to use preg_replace_callback(). Same when you use the modifier e and get "Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead". See: Replace preg_replace() e modifier with preg_replace_callback
If you want to put everything together and create a function that also works for multidimensional arrays case-insensitive you can do something like this:
<?php
function preg_replace_deep($search, $replace, $subject)
{
if (is_array($subject))
{
foreach($subject as &$oneSubject)
$oneSubject = preg_replace_deep($search, $replace, $oneSubject);
unset($oneSubject);
return $subject;
} else {
return preg_replace($search, $replace, $subject);
}
}
?>
##Loops while / for / foreach method (NOT binary safe; case-sensitive)
Now of course besides all of those functions you can also use a simple loop to loop through the string and replace each search => replace pair which you have.
But this gets way more complex when you do it binary safe, case-insensitive and for multidimensional arrays than just using the functions above. So I won't include any examples here.
Affected String
Right now all methods shown above do the replacement over the entire string. But sometimes you want to replace something only for a certain part of your string.
For this you probably want to/can use substr_replace(). Or another common method is to use substr() and apply the replacement only on that particular substring and put the string together afterwards. Of course you could also modify your regex or do something else to not apply the replacement to the entire string.
str_replace is sufficient for simple replacement jobs (such as replacing a single letter), but the use of preg_replace is generally advised (if you want something more flexible or versatile), because it's flexible and versatile. And as the 'a' is just an example...:
$String = preg_replace('/<string>/','<replacement>',$String);
Or if you want multiple replacements at once:
$String = preg_replace(array('/<string 1>/','/<string 2>/'),array('<replacement 1>','<replacement 2>'),$String);
preg_replace can, unfortunately, be quite tricky to use. I recommend the following reads:
http://php.net/manual/en/function.preg-replace.php
http://www.phpro.org/tutorials/Introduction-to-PHP-Regex.html
Also, if you decide to use str_replace(), and your replacement needs to be case-sensitive, you're going to need str_ireplace().
This can work also without of any of PHP string functions, here changing your 'a' to '&' ampersand character:
for ($i=0; $i<strlen($str); $i++){
if ($str[$i] == 'a'){
$str[$i] = '&';
}
}
echo $str;
Use function preg_replace()
$text ='this is the old word';
echo $text;
echo '<br>';
$text = preg_replace('/\bold word\b/', 'NEW WORD', $text);
echo $text;