0

Basically from a database I am getting data that is formatted like this nameofproject101 Now this could continue to increase so eventually it could be nameofproject1001 my question is how can I trim off the number and just get the name of the project. I thought about using substr but since I dont know the length always I cant really do that. Since the numbers differ I dont think I can use str_replace is there any way to accomplish this?

4
  • Use regular expression to strip out trailing numbers. stackoverflow.com/questions/2123334/… Commented Feb 5, 2012 at 18:02
  • Will the name of the project itself contain numbers? Commented Feb 5, 2012 at 18:03
  • @erisco From the database yes it is stored like 'nameofproject101' I need it to be 'nameofproject', but what I need to do with the data, I dont need the numbers so I need them stripped off. Commented Feb 5, 2012 at 18:04
  • @atrljoe I believe erisco was asking whether the name (without the trailing numbers) could contain numbers. E.g. r2d2translator1001. Commented Feb 5, 2012 at 18:11

4 Answers 4

3

It sounds like something is way off about your database scheme. You should probably try to do refactor/normalize your scheme.

But in the meantime, you can use rtrim() to trim all numbers off of the right side.

$val = rtrim($val, '0123456789');

Examples

Input               Output
nameofproject1001   nameofproject
nameofproject       nameofproject
n4me0fproj3ct1001   n4me0fproj3ct
Sign up to request clarification or add additional context in comments.

Comments

1

for string like, project12V123, It is better to do this

$text = `project12V123`;
$text = preg_replace('/([\w]+)([^0-9])([0-9])+$/', '$1$2', $text);

Will return:

Project12V

or use rtrim:

$text = rtrim($text,'0123456789'); 

Comments

0

You should definitely use regular expressions:

$fullname = "nameofproject101";
preg_match("/([a-z]+)([0-9]+)/i", $fullname, $matches);
$name   = $matches[1];
$number = $matches[2];
echo "'$fullname' is '$name' followed by '$number'";

1 Comment

This will turn version2project101 into version. OP probably wants version2project.
-1
preg_replace('/[^a-z]/i', '', $string); 

2 Comments

@Kristian That's what I was hinting at. ;)
The above will turn r2d2translator1001 into rdtranslator. Probably not what OP wants.

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.