Jump to content

removing all after last number in string.


jasonc

Recommended Posts

i wish to remove all content from a string after the last number...

 

say the string is '123abcde'  i need it to be just '123'

and if say '237473nejejd484235'  then it should be '237473'

 

only the first part which are numbers should remain in the string.

 

how can i do this?

 

thanks

 

Uhh...

 

$newstr = eregi_replace('([0-9]+)(.+)', '\\1', $str);

 

thinking about it is it possible to add a '&' after the last number in the first part of the string?  but only if the string has something after that last number.

 

 

and if the characters after that last number is not already a '&'

 

Google RSS has got a load of incorrect links!  it has all the old link which do not have the '&' in them!

sometimes the hard way is the better option - it never fails. With eregi_replace()

you're relying on the code of another person. PHP is full of quirks and bugs-it doesn't matter- there is always another way to get from point A to B.

 

$str="165890456732245";

$number = "";

for($i = 0; $i < strlen($str); $i++){

 

if(is_numeric($str[$i])){

 

$number .= $str[$i];

if(!is_numeric($str[$i + 1])){

break;

}

}

}

echo $number;

<?php
$str = '23747332434asdfj234234234';
$str = preg_replace('~(?!^|\d).+~m', '', $str);
echo $str;
?>

 

 

Tested to match the "unwanted portion of the string" like you described on all these samples:

23747332434asdfj234234sfsdfdsf234
23747323dsf32434asdfj2asdf34234234
3423423
2
324

 

Try it out here:

http://nancywalshee03.freehostia.com/regextester/regex_tester.php?seeSaved=e775bc3a

regex_tester.php?seeSaved=e775bc3a.gif

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.