Ramil
Ramil

Reputation: 91

Remove string before period in PHP

Is there a way to remove everything before and including the last instance of a dot(.) in a string?

I have these following strings:

  1. packageName.appName.moduleName.eventName.pageNameX
  2. packageName.appName.moduleName.pageNameY
  3. packageName.appName.pageNameZ
  4. packageName.pageNameA

And I want to have:

  1. pageNameX
  2. pageNameY
  3. pageNameZ
  4. pageNameA

I have tried:

preg_replace('/^.*.\s*/', '', $theString);

but it doesn't work.

Upvotes: 0

Views: 245

Answers (3)

coderodour
coderodour

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

Ryan Tuosto
Ryan Tuosto

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

Wiktor Stribiżew
Wiktor Stribiżew

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

Related Questions