Jump to content

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!

Uhh...

 

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

 

hi thanks for this but..

if the string is just a number with nothing at the end it takes the last number off !

 

how do i keep the numbers in the start of the string?

 

thanks

 

 

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.