2

I want to remove the part from this text. ACCES_ALL_AREAS_1. Now the text is like this and I want to make it like ACCES_ALL_AREAS. I used PHP explode with for loops. That didn't work. And also the word count is not static. Not always 3 as above example.

  • A_PLACE_IN_THE_ABC_3 -> A_PLACE_IN_THE_ABC
  • ACCES_ALL_AREAS_1 -> ACCES_ALL_AREAS
2
  • Will there always be a number after the last underscore? Commented Jun 24, 2016 at 16:42
  • @ObjectManipulator , yeah sure..Always there's a number at the end Commented Jun 25, 2016 at 13:10

3 Answers 3

10

I would probably do this:

$string = preg_replace('/_\d+$/', '', $string);
  • Replace _ and digits at end $ of string

For fun you could also do this:

$string = rtrim($string, '_1234567890');

Or with a range:

$string = rtrim($string, '_0..9');

Another way:

$parts  = explode('_', $string);
array_pop($parts);
$string = implode('_', $parts);
  • explode on _ to an array
  • pop the last element off of the array
  • implode array on _ back into a string
Sign up to request clarification or add additional context in comments.

2 Comments

Just to show a demo on regex101.com with your expression.
I like the last example. You can also get the last element value by changing the code like so $last = array_pop($parts);.
1

Let's see if you have a number of not, it will remove the last array whatsoever it is, give it a try:

<?php
$string = "A_PLACE_IN_THE_ABC_3";
$ex = explode('_', $string); // break array
$c = count($ex); // total array
$rm = $c - 1; // 1 place to 0
unset ($ex[$rm]); // Remove unwanted array
$new = join('_', $ex); // regenerate string
echo "New String: ". $new;

Another option is substr:

$string = "A_PLACE_IN_THE_ABC_3";
echo substr($string, 0, -2); // remove last 2 strings

Comments

-1

Try this:

$mystring = "A_PLACE_IN_THE_ABC_3";
$pos = strrpos($mystring, "_");
$result = substr($mystring,0, $pos);   //  A_PLACE_IN_THE_ABC

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.