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;
Related
I've started with preg_replace in PHP and I wonder how I can replace only first matching array key with a specified array value cause I set preg_replace number of changes parameter to '1' and it's changing more than one time anyways. I also splitted my string to single words and I'm examining them one by one:
<?php
$internal_message = 'Hey, this is awesome!';
$words = array(
'/wesome(\W|$)/' => 'wful',
'/wful(\W|$)/' => 'wesome',
'/^this(\W|$)/' => 'that',
'/^that(\W|$)/' => 'this'
);
$splitted_message = preg_split("/[\s]+/", $internal_message);
$words_num = count($splitted_message);
for($i=0; $i<$words_num; $i++) {
$splitted_message[$i] = preg_replace(array_keys($words), array_values($words), $splitted_message[$i], 1);
}
$message = implode(" ", $splitted_message);
echo $message;
?>
I want this to be on output:
Hey, that is awful
(one suffix change, one word change and stops)
Not this:
Hey, this is awesome
(two suffix changes, two word changes and back to original word & suffix...)
Maybe I can simplify this code? I also can't change order of the array keys and values cause there will be more suffixes and single words to change soon. I'm kinda newbie in php coding and I'll be thankful for any help ;>
You may use plain text in the associative array keys that you will use to create dynamic regex patterns from, and use preg_replace_callback to replace the found values with the replacements in one go.
$internal_message = 'Hey, this is awesome!';
$words = array(
'wesome' => 'wful',
'wful' => 'wesome',
'this' => 'that',
'that' => 'this'
);
$rx = '~(?:' . implode("|", array_keys($words)) . ')\b~';
echo "$rx\n";
$message = preg_replace_callback($rx, function($m) use ($words) {
return isset($words[$m[0]]) ? $words[$m[0]] : $m[0];
}, $internal_message);
echo $message;
// => Hey, that is awful!
See the PHP demo.
The regex is
~(?:wesome|wful|this|that)\b~
The (?:wesome|wful|this|that) is a non-capturing group that matches any of the values inside, and \b is a word boundary, a non-consuming pattern that ensures there is no letter, digit or _ after the suffix.
The preg_replace_callback parses the string once, and when a match occurs, it is passed to the anonymous function (function($m)) together with the $words array (use ($words)) and if the $words array contains the found key (isset($words[$m[0]])) the corresponding value is returned ($words[$m[0]]) or the found match is returned otherwise ($m[0]).
I'm working in Joomla developing a Module where I need to strip this snippet from the $article->text and extract the part number to have its contents stored in $part_number.
{myplugin}ABCDEF1234,"Flux Capacitor"{/myplugin}
I've been trying to work something out, but I can't get it working:
$re = '/\{myplugin\}(\w+),[^{}]+\{\/myplugin\}/';
$subst = '';
$result = preg_replace($re, $subst, $article->text);
$article->text = $result;
But this doesn't return the part number so I can put it in $part_number. Can this be done in one regular expression operation, or should it be one to extract the number number and a second to remove the snippet from $article->text?
The intention is to have {myplugin}ABCDEF1234,"Flux Capacitor"{/myplugin} removed from $article->text and have its part number such as ABCDEF1234 copied from this snippet and stored in PHP variable $part_number.
I would recommend you to use preg_match:
$s='{myplugin}ABCDEF1234,"Flux Capacitor"{/myplugin}';
preg_match('/{myplugin}(\w+)\,"(.+)"{\/myplugin}/', $s, $result);
$result will be:
array (size=3)
0 => string '{myplugin}ABCDEF1234,"Flux Capacitor"{/myplugin}' (length=48)
1 => string 'ABCDEF1234' (length=10)
2 => string 'Flux Capacitor' (length=14)
UPD:
$article->text = str_replace($result[0], '', $article->text);
$part_number = $result[1];
Yes you can remove the plugin substring from $article->text AND declare $partnumber in one hit.
Code: (Demo)
$article=(object)['text'=>'Some leading text {myplugin}ABCDEF1234,"Flux Capacitor"{/myplugin} some trailing text'];
$re = '~\{myplugin\}([^,]+),[^{]+\{/myplugin\}~';
$subst = '';
$article->text=preg_replace_callback($re,function($m)use(&$partnumber){ $partnumber=$m[1]; return '';},$article->text,1);
echo $article->text;
echo "\n";
echo $partnumber;
Output:
Some leading text some trailing text
ABCDEF1234
By switching from preg_replace() to preg_replace_callback() you can call an anonymous function to carry out the two tasks. First, the new variable $partnumber is declared, then the empty string replaces the greater plugin substring (fullstring match).
use(&$partnumber) allows you to declare a modifiable variable inside the callback function which will be available in the global scope.
My method assumes that there will only ever be 1 found $partnumber (this is why there is a 1 for a value in the 4th parameter. If there are two or more, then the 4th parameter must be removed and the $partnumber assignment must be written as an array $partnumber[]=$m[1] so that earlier matches aren't overwritten by later ones.
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);
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 a string like abcdefg123hijklm. I also have an array which contains several strings like [456, 123, 789].
I want to check if the number in the middle of abcdefg123hijklm exists in the array.
How can I do that? I guess in_array() won't work.
So you want to check if any substring of that particular string (lets call it $searchstring) is in the array?
If so you will need to iterate over the array and check for the substring:
foreach($array as $string)
{
if(strpos($searchstring, $string) !== false)
{
echo 'yes its in here';
break;
}
}
See: http://php.net/manual/en/function.strpos.php
If you want to check if a particular part of the String is in the array you will need to use substr() to separate that part of the string and then use in_array() to find it.
http://php.net/manual/en/function.substr.php
Another option would be to use regular expressions and implode, like so:
if (preg_match('/'.implode('|', $array).'/', $searchstring, $matches))
echo("Yes, the string '{$matches[0]}' was found in the search string.");
else
echo("None of the strings in the array were found in the search string.");
It's a bit less code, and I would expect it to be more efficient for large search strings or arrays, since the search string will only have to be parsed once, rather than once for every element of the array. (Although you do add the overhead of the implode.)
The one downside is that it doesn't return the array index of the matching string, so the loop might be a better option if you need that. However, you could also find it with the code above followed by
$match_index = array_search($matches[0], $array);
Edit: Note that this assumes you know your strings aren't going to contain regular expression special characters. For purely alphanumeric strings like your examples that will be true, but if you're going to have more complex strings you would have to escape them first. In that case the other solution using a loop would probably be simpler.
You can do it reversely. Assume your string is $string and array is $array.
foreach ($array as $value)
{
// strpos can return 0 as a first matched position, 0 == false but !== false
if (strpos($string, $value) !== false)
{
echo 'Matched value is ' . $value;
}
}
Use this to get your numbers
$re = "/(\d+)/";
$str = "abcdefg123hijklm";
preg_match($re, $str, $matches);
and ( 123 can be $matches[1] from above ):
preg_grep('/123/', $array);
http://www.php.net/manual/en/function.preg-grep.php