Branko
Branko

Reputation: 13

PHP remove all characters before certain string

I need to grep certain string(with bold) from any string with regular expression.

Sample data:

"drog stabilizatorja Meyle RE 16-16 060 0004/HD"

"koncnik Meyle RE 16-16 020 0013"

"gumica stabilizatorja Meyle RE 16-14 079 9404/S"

I think it would be ok if I cut all characters before first number in string. I am not sure how to do it.

Upvotes: 1

Views: 601

Answers (5)

Replace the string...

$str = "drog stabilizatorja Meyle RE 16-16 060 0004/HD";
$str = preg_replace( '/.*([^\\d*](\\d.*))/', '\1', $str);
echo $str;

Upvotes: 0

karthik manchala
karthik manchala

Reputation: 13640

I think it would be ok if I cut all characters before first number in string. I am not sure how to do it.

You can use ^.*?(?=\d) as far as your above statement is concerned. And replace with '' (empty string).

Demo and explanation

Note: If you want to extract out digits Kasra's solution is the best and if you want to match and replace you can use this.

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107287

You can use the following regex :

'\d+-\d+.*'

Upvotes: 1

jeromegamez
jeromegamez

Reputation: 3551

Kasra's solution is the most simple one and works perfectly. However, if you want to ensure the specific pattern that your samples seem to have, this would be a "specialized" method:

$samples = array(
    "drog stabilizatorja Meyle RE 16-16 060 0004/HD",
    "koncnik Meyle RE 16-16 020 0013",
    "gumica stabilizatorja Meyle RE 16-14 079 9404/S"
);

$result = array();

foreach ($samples as $sample) {
    if (preg_match('@(\d{2}\-\d{2}\s\d{3}\s\d{4}(/\w+)?)@', $sample, $matches)) {
        $result[] = $matches[0];
    }
}

print_r($result);

// Output:
//
// Array
// (
//     [0] => 16-16 060 0004/HD
//     [1] => 16-16 020 0013
//     [2] => 16-14 079 9404/S
// )

(\d{2}\-\d{2}\s\d{3}\s\d{4}(\/\w+)?)

Regular expression visualization

Debuggex Demo

Upvotes: 0

ByteHamster
ByteHamster

Reputation: 4951

Using regex:

$str = "drog stabilizatorja Meyle RE 16-16 060 0004/HD";
preg_match("/[^\\d*](\\d.*)/", $str, $matches);
echo $matches[1];

Output:

16-16 060 0004/HD

Upvotes: 0

Related Questions