Reputation: 91
Is there a way to remove everything before and including the last instance of a dot(.) in a string?
I have these following strings:
packageName.appName.moduleName.eventName.pageNameX
packageName.appName.moduleName.pageNameY
packageName.appName.pageNameZ
packageName.pageNameA
And I want to have:
pageNameX
pageNameY
pageNameZ
pageNameA
I have tried:
preg_replace('/^.*.\s*/', '', $theString);
but it doesn't work.
Upvotes: 0
Views: 245
Reputation: 1057
This function will split the package path into components using the period as a delimiter. Then it will return the last component after the last period using the number of components retrieved in array upon splitting the package path.
function get_package_name($in_package_path){
// Split package path into components at the periods.
$package_path_components = explode('.',$in_package_path);
// Get the total number of items in components array
// and subtract 1 to get array index as array indexes start at 0.
$last_package_path_component_index = count($package_path_components)-1;
// Return the last component of the package path.
return $package_path_components[$last_package_path_component_index]
}
Upvotes: 0
Reputation: 1951
substr($str, strrpos($str, '.')+1);
strrpos()
will return the position of the last instance of a character in a string. Use that value + 1 as the starting position in substr()
to get everything after that.
Upvotes: 2
Reputation: 626689
You may match these substrings with
$s = "packageName.appName.moduleName.eventName.pageNameX";
preg_match('~[^.]+$~', $s, $match);
echo $match[0];
See the regex demo and a PHP demo.
Details:
[^.]+
- 1 or more chars other than .
$
- end of string.Upvotes: 2