开发者

Stripping leading character from an alphanumeric string using php

开发者 https://www.devze.com 2023-02-11 22:16 出处:网络
I\'ve got several strings of the type id1开发者_如何学运维, id2, id125, id1258, etc. What I want to achieve using php is to strip the word \"id\" from those strings and get only the numbers in intege

I've got several strings of the type id1开发者_如何学运维, id2, id125, id1258, etc.

What I want to achieve using php is to strip the word "id" from those strings and get only the numbers in integer format in php. How can I do this?


If these strings only begin with the string id:

$number = intval(ltrim($number, 'id'));


You can use preg_replace like this:

preg_replace('/\D/', '', $your_string);

Where \D represents anything not a number. So it is replaced with an empty string leaving you with just number.

Example:

$string = 'id1258';
$string = preg_replace('/\D/', '', $string);
echo $string;

Result:

1258


This seems like a good case for a simple substr:

$number = intval(substr($string, 2));


If all strings begin with id then just make it simple:

$num = intval( substr( $string, 2 ) );
0

精彩评论

暂无评论...
验证码 换一张
取 消