How to split numbers from a string using php

Do you know How to split numbers from a string using PHP? maybe you don’t, that’s why you are here right?. I will show you that

Here we have a string

My customer id is 12457 and phone number is 8147588715

This is our string we have to assign this to a variable.

$str = "My customer id is 12457 and phone number is 8147588715";

Now we have to use explode()  Function to split this string.

$split = explode(" ",$str);

then we are looping all the words and find the numbers

foreach($split as $words)
   {
      echo $words;
   }

Now we taking the INT values from the $words

$numberinthisstring =  (int) filter_var($words, FILTER_SANITIZE_NUMBER_INT);

Now we check if the has any digits, display that



if($numberinthisstring!=0)
       {
           echo $numberinthisstring.'<br>';
       }

 

Now i will give you the complete source code,

$str = "My customer id is 12457 and phone number is 8147588715";
$split = explode(" ",$str);
foreach($split as $words)
{
    $numberinthisstring =  (int) filter_var($words, FILTER_SANITIZE_NUMBER_INT);
    if($numberinthisstring!=0)
    {
        echo $numberinthisstring.'<br>';
    }
}

And this will be the result

So you can list out all the numbers in the string . Hope this helpful for you .

 

Post Your Questions on our forum

Post a question on Forum

Ajith Jojo Joseph

Self taught, dedicated young entrepreneur with many licensed products under his sleeve. Passionate about technology, business and excellence in general.

Share with your friends:

Comments are closed.

How to get the next value of an array and loop it in the array in PHP

Do you know How to get the next value of an array and loop it in the array in PHP […]

July 28, 2023

New Open Source CRM for project Management and Invoicing

I’m excited to announce the launch of my new open source project: Gmax CRM. an invoicing and project management tool […]

December 31, 2022

Post View Counts WordPress plugin (Documentation)

The Post View Counts plugin is a simple tool for tracking and displaying the number of views for each post […]

December 30, 2022

How to create Laravel Flash Messages

Laravel flash messages are a convenient way to display one-time notifications to the user after a form submission or other […]

December 22, 2022

Digital Marketing Toolkit

Get Free Access to Digital Marketing Toolkit. You can use all our tools without any limits

Get Free Access Now