php - Group words in string with count using function -


i need in getting count of array in string.

i have array 5 words :

$array_planet = array('[sun]', '[moon]', '[mercury]', '[venus]', '[mars]'); 

and i've many strings :

$string_source = 'blabla[sun][sun]blabla[moon][moon][moon]blabla[sun][sun][sun][sun]blabla[venus]'; 

i need function return :

$string_out = 'blabla[sun][2]blabla[moon][3]blabla[sun][4]blabla[venus][1]'; 

blabla can length , values.

just use preg_replace_callback():

$string_source = preg_replace_callback('/(\[[^\[\]]+\])+/', function($matches) {    return $matches[1].'['.(strlen($matches[0])/strlen($matches[1])).']'; }, $string_source); 

note, not rely on planets array because regex replace don't need it.

fiddle available here


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -