Jin Yong
Jin Yong

Reputation: 43778

Any way that to cut only number or char from the string in php

Does anyone know how can I cut only number or char from the string in php?

Example

$test = '12b';

any way that I can only cut the number from the variable: 12? also and way that I can only cut out the char: b?

NOTE: the $test string flexible to changed.. means it could come with '123b', '1a'...

Upvotes: 0

Views: 674

Answers (2)

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74252

preg_match could be made use of:

<?php

$test = '12b';
preg_match( '/^(\d+)(\w+)$/', $test, $matches );
$digits     = $matches[1];
$characters = $matches[2];

?>

Upvotes: 2

Dagg Nabbit
Dagg Nabbit

Reputation: 76756

Try this:

  $test='12b'; 

  // ...

  $numeric = preg_replace('/[^\d]/', '', $test);
  echo $numeric; // 12

  $alpha = preg_replace('/[^a-z]/i', '', $test);
  echo $alpha; // b

This will work for any combination of characters. All the digits will appear in $numeric, and all latin alphabet letters will appear in $alpha.

This will still work if the letters and numbers are reversed, or if other symbols appear in the string.

Upvotes: 1

Related Questions