Domanda

I need some help in getting the count of the array in string.

I have an array with 5 words :

$array_planet = array('[Sun]', '[Moon]', '[Mercury]', '[Venus]', '[Mars]');

and I've many strings that look like :

$string_source = 'blabla[Sun][Sun]blabla[Moon][Moon][Moon]blabla[Sun][Sun][Sun][Sun]blabla[Venus]';

I need a function to return :

$string_out = 'blabla[Sun][2]blabla[Moon][3]blabla[Sun][4]blabla[Venus][1]';

blabla can be any length and values.

È stato utile?

Soluzione

Just use preg_replace_callback():

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

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

Fiddle is available here

Altri suggerimenti

Use preg_replace_callback() to achieve this:

$result = preg_replace_callback('/(\[.*?])+/', function($m) {
    return $m[1].'['.substr_count($m[0], $m[1]).']';
}, $string_source);

Output:

blabla[Sun][2]blabla[Moon][3]blabla[Sun][4]blabla[Venus][1]

Demo

I would use preg_match_all to get the parts from your string, so you end up havin something like this:

array = (
 0= > 'blabla[Sun][Sun]',
 1 => 'blabla[Moon][Moon][Moon]',
 2 => 'blabla[Sun][Sun][Sun][Sun]',
 3 => 'blabla[Venus]'
);

Then iterate over the array and use str_replace and substr_count.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top