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 data from a model on all pages in Laravel – Simple Way

Do you know How to get data from a model on all pages in Laravel ? In this blog post, […]

August 5, 2022

Export html table to excel, pdf, csv format using Datatable

Do you know how to export html table to excel, pdf, CSV, or excel format using Datatable? If you don’t […]

August 4, 2022

How to create a Laravel Collection From JSON

Today i have to create a laravel collection from a JSON object. I search on the internet and I cant […]

August 3, 2022

Instagram Hashtag API PHP and JavaScript Integration with RapidAPI

Do you know how to integrate Instagram Hashtag API with your website? In this tutorial, I will show you how […]

August 2, 2022

Digital Marketing Toolkit

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

Get Free Access Now