1

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.

0

5 Answers 5

1

You can use the following regex :

'\d+-\d+.*'
Sign up to request clarification or add additional context in comments.

Comments

0

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

4 Comments

Thank you. What if I have other characters in string like /. Sample string: "drog stabilizatorja Meyle AU/SE/SK/VW 116 060 0000/HD"
drog stabilizatorja Meyle AU/SE/SK/VW 116 060 0000/HD gets trimmed to 116 060 0000/HD. Isn't this what you want to get?
Sorry, it is ok, I had to refresh :)
Please accept this answer (tick the checkbox), so someone who visits this page later can directly see what he should try.
0

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

Comments

0

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.

Comments

0

Replace the string...

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.