Finding the correct appearance order

I have a PHP line, for example this line (haystack):

$text = "here is a sample: this text, and this will be exploded. this also | this one too :)"; 

Now I would like to set up the PHP array in the order in which the needle appears in the string. So this is my needle:

 $needle = array(",",".","|",":"); 

When searching for a needle in the string $text this should be the output:

 Array ( [0] => : [1] => , [2] => . [3] => | [4] => : ) 

Can this be done in PHP?

This is similar to question , but for JavaScript.

+4
source share
4 answers

str_split can be convenient here

 $text = "here is a sample: this text, and this will be exploded. this also | this one too :)"; $needles = array(",",".","|",":"); $chars = str_split($string); $found = array(); foreach($chars as $char){ if (in_array($char, $needles)){ $found[] = $char ; } } 
+1
source

This will give you the expected result:

  <?php $haystack= "here is a sample: this text, and this will be exploded. this also | this one too :)"; $needles = array(",",".","|",":"); $result=array(); $len = strlen($haystack) ; for($i=0;$i<$len;$i++) { if(in_array($haystack[$i],$needles)) { $result[]=$haystack[$i]; } } var_dump($result); ?> 
0
source
 $string = "here is a sample: this text, and this will be exploded. th is also | this one too :)"; preg_match_all('/\:|\,|\||\)/i', $string, $result); print_r( array_shift($result) ); 

use preg_match_all

pattern \:|\,|\||\)

Working demo ...

0
source

Ok let it just for fun

 $string = "here is a sample: this text, and this will be exploded. this also | this one too :)"; $needle = array(",",".","|",":"); $chars = implode($needle); $list = array(); while (false !== $match = strpbrk($string, $chars)) { $list[] = $match[0]; $string = substr($match, 1); } var_dump($list); 

You can see his work - Read about strpbrk

Description

strpbrk returns a string after the first matching character

Turn 1

 $string = "here is a sample: this text, and this will be exploded. this also | this one too :)"; // strpbrk matches ":" $match = ": this text, and this will be exploded. this also | this one too :)"; // Then, we push the first character to the list ":" $list = array(':'); // Then we substract the first character from the string $string = " this text, and this will be exploded. this also | this one too :)"; 

Turn 2

 $string = " this text, and this will be exploded. this also | this one too :)"; // strpbrk matches "," $match = ", and this will be exploded. this also | this one too :)"; // Then, we push the first character to the list "," $list = array(':', ','); // Then we substract the first character from the string $string = " and this will be exploded. this also | this one too :)"; 

And so on, until it works out

Turn 5

 $string = ")"; // strpbrk doesn't match and return false $match = false; // We get out of the while 
0
source

Source: https://habr.com/ru/post/1501666/


All Articles