Search a word in string from array of words using php

If you have to find any word in a string, Its very easy to do this by
functions strpos and stripos.

strpos is using for case sensitive check and stripos for case insensitive check.

But problem comes when i have to search a word in string from array of words.

I was working on an e-commerce project "DealsBro".
I had to find Internal memory and colour, if given in any product name.

Suppose I have list of memory sizes. I have added in an array.

$sizes = array('4 GB','4GB','8 GB','8GB','16 GB','16GB','32 GB','32GB','64 GB','64GB','128 GB','128GB');

I want to know memory size given in a product name. For example:

$title = 'Samsung Galaxy Core Prime 4G (Charcoal Grey, 8 GB)'; 

I want to create a script where i have to give an input ($title) and want result like '8 GB'

I have achieved this by following script I had created:

For Memory Size:

function getSizeOfProductName($string){
$sizes = array('4 GB','4GB','8 GB','8GB','16 GB','16GB','32 GB','32GB','64 GB','64GB','128 GB','128GB');
$check = array_filter($sizes, function($url)  use ($string){
 
if(stripos($string, $url))
return $url;
});
$newcheck = array_values($check);
return $size = $newcheck[0];
}


Step 1: Copy above code in your php page.
Step 2: Write following code:
             $title = 'Samsung Galaxy Core Prime 4G (Charcoal Grey, 8 GB)'; // REPLACE PRODUCT NAME HERE
             $size = getSizeOfProductName($title);

step 3: Now $size is returning '8 GB' here.

Same logic you can use for colour also.

Please try this. If you find any error, comment here. I will try to reply as soon as possible.
If you find it helpful, please share it on social sites.
0 Comments
Disqus
Fb Comments
Comments :

0 comments:

Post a Comment