How can I filter text out of a string containing numbers and text in PHP

808 Views Asked by At

I want to filter out the text out of a string which contain numbers and letters. Take for example,

 input       expected result(output)
R543.32 --->    R
gbp6.99 --->    gbp

How would I do that? I used filter_var() to get the numbers on their own, but cannot seem to find how to get the text on its own, at least not in a way that is scalable.

$buying_price_filtered = filter_var($buying_price, FILTER_SANITIZE_NUMBER_FLOAT, 
 FILTER_FLAG_ALLOW_FRACTION);
1

There are 1 best solutions below

0
Hirumina On

You can simply use preg_replace to remove the integers and special characters from the strings that you have.

Here i'll add a-z and A-Z together since there might be both capital and simple letters. So that you will get all the letters that are there in the word.

$str = 'R543.32';
$newstr =  preg_replace("/[^a-zA-Z]/", "", $str);
echo $newstr;
//will return you the letters for the above ex: R will be the return

For further reference you can go here