Prachi Varaiya
Prachi Varaiya

Reputation: 175

Remove the data after a certain characters in a string using php

$title=Canon PowerShot SX130IS 12.1 MP Digital Camera with 12x Wide 
Angle Optical Image Stabilized Zoom with 3.0-Inch LCDCanon PowerShot 
SX130IS 12.1 MP Digital Camera with 12x Wide Angle Optical Image 
Stabilized Zoom with 3.0-Inch LCD

Want output as:

$title = Canon PowerShot SX130IS

Without use of strpos in php because there is a group of data on which positions are different for string.Hence want to remove the data after a pattern in which as a e.g. after 12.1 MP I want to remove everything. So anyone can tell me what pattern I can write for it. e.g. 12.1 MP camera(red),14.1 MP camera(blue) many characters written after that to be removed of from it Please anyone give me the required pattern for it!!

Upvotes: 0

Views: 48

Answers (3)

tobifasc
tobifasc

Reputation: 765

If you want to handle different megapixels you could use something like this:

preg_replace('/\s\d+\.?\d*\sMP.*/', "", "Canon PowerShot SX130IS 15.4 MP Digital Camera blabla");

Another variation to also catch "...SX130IS/15.4 MP..." and "...15.4MP..." would be:

preg_replace('/(\s|\/)\d+\.?\d*\s?MP.*/', "", "Canon PowerShot SX130IS 15.4 MP Digital Camera blabla");

Upvotes: 1

Puni
Puni

Reputation: 1294

This will return the strings value based on the MP position.

    function foo($title) {        
        $title_array = explode(' ',$title);
        foreach ($title_array as $key => $value) {
            if($value === "MP"){
                $title = implode(' ',array_slice($title_array, 0, $key));
                return $title;
            }
        }
    }

    foo($title);

Upvotes: 1

NickOS
NickOS

Reputation: 804

list($result) = explode("MP", $title, 2);
$result[0] = 'Canon PowerShot SX130IS 12.1 MP'

Upvotes: 0

Related Questions