Tuesday, 4 October 2016

php - Substituting Words in a Body of Text with User Input via Multidimensional Arrays



I have two sets of data stored in multidimensional arrays. One stores regular expressions which will be used to find whole words within a larger body of text:



Array
(
[red] => Array
(
[0] => ~\b(a)\b~i
[1] => ~\b(b)\b~i
[2] => ~\b(c)\b~i
)
[orange] => Array
(
[0] => ~\b(d)\b~i
)
[green] => Array
(
[0] => ~\b(e)\b~i
)
)


And the other contains what to replace those matches with:



Array
(
[red] => Array
(
[0] => A
[1] => B
[2] => C
)
[orange] => Array
(
[0] => D
)
[green] => Array
(
[0] => E
)
)


For exemplary purposes, let's say the body of text is:




The quick brown fox jumps over the lazy dog. a The quick brown fox
jumps over the lazy dog. b The quick brown fox jumps over the lazy
dog. c The quick brown fox jumps over the lazy dog. d The quick
brown fox jumps over the lazy dog. e




The PHP function preg_replace doesn't handle multidimensional arrays, so how would I go about accomplishing this?


Answer



To deal with your arrays, just use a foreach loop:



foreach($reg_cats as $key=>$reg_cat) {
$yourstring = preg_replace($reg_cat, $rep_cats[$key], $yourstring);
}


$reg_cats is your array with regex, $rep_cats is your array with replacements. Since they have the same keys and the subarrays the same size, you can do that.



In the case you don't need to transform what you match (here you want to change the letter to uppercase), you can use a single associative array:



$corr = array('$0'    =>  '~\b(?:a|b|c)\b~i',
'$0' => '~\bd\b~i',
'$0' => '~\be\b~i');

$result = preg_replace($corr, array_keys($corr), $yourstring);

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...