Jump to content

How do I use substr to remove numbers only?


Jeffro

Recommended Posts

Actually.. I'm assuming I use substr, but feel free to correct me if there's a better way. 

 

I have an ever changing list that I need to knock the from numbers off of.  The numbers can be different lenghts, such as..

 

1. item number 1

12. item number 12

101. item number 101

 

How do I remove the number, period and blank space for each item, since the length of the number may always differ?

 

Thank you!

you don't want to use substr, you want to use a regular expression.

 

look into preg_replace

 

something like:

<?php

$value = "12345. some some string";
$match = "/^[0-9]. /";
$replace = "";
$value = preg_replace($match,$replace,$value);

?>

 

//this probably won't work 'cause i suck at regex, but someone can come along and fix it :)

drisate's explode() option is how I probably would have done it since regex is annoying.  the only downside is if your text string may have more than one "." in it.  inwhich case your array will have more than just 2 levels.

 

 

also,

wildteen88 is much better at regex then me :)

If you use the explode method, you can use the little used third parameter to explode to limit the number of parts returned:

<?php
$strs = array('1. item number 1',
'12. item number 12',
'101. item number 101');
foreach ($strs as $str) {
   list (,$str) = explode('.',$str,2);
   echo ltrim($str) . "<br>\n";
}
?>

 

Ken

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.