Question

I'm trying to use preg_match_all to return an separate arrays for various elements in a CamelCase string. In my example, I'm attempting to obtain the prefix of a string in one array and everything else ( the camelcase portion of the string ) split up into a second array. For instance, get_BookGenreTitle is supposed to return get_ in one array, and another array containing the words Book, Genre, and Title. Or, for further demonstration, post_PersonID would return post_ in one array, and another array containing the word ID.

I have the following chunk of code which get's it done, but somewhat sloppily. When it returns the array containing the prefix, the array also contains a number of blank elements equal to the number of CamelCased elements.

<?php

$var = "get_BookGenreTitle";

preg_match_all("/(get_|post_)?([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)/", $var, $matches);

print_r($matches);

?>

Returns: Array ( [0] => Array ( [0] => get_Book [1] => Genre [2] => Title ) [1] => Array ( [0] => get_ [1] => [2] => ) [2] => Array ( [0] => Book [1] => Genre [2] => Title ) )

I was wondering if there is someway to return both an array with the prefix and a separate array with the CamelCase elements, but with no blank elements in the prefix array.

End Result Example: Array ( [0] => Array ( [0] => get_Book [1] => Genre [2] => Title ) [1] => Array ( [0] => get_ ) [2] => Array ( [0] => Book [1] => Genre [2] => Title ) )

Was it helpful?

Solution

every time something is not found but asked for within () you will get an empty array element. i can not remember any options to unset this behavior.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top