4

I have a string like this 05/15/2015 09:19 PM pt_Product2017.9.abc.swl.px64_kor_7700 I need to select the pt_Product2017.9.abc.swl.px64_kor from that. (start with pt_ and end with _kor)

$str = "05/15/2015 09:19 PM pt_Product2017.9.abc.swl.px64_kor_7700";
preg_match('/^pt_*_kor$/',$str, $matches);

But it doesn't work.

0

3 Answers 3

8

You need to remove the anchors, adda \b at the beginning to match pt_ preceded with a non-word character, and use a \S with * (\S shorthand character class that matches any character but whitespace):

preg_match('/\bpt_\S*_kor/',$str, $matches);

See regex demo

In your regex,^ and $ force the regex engine to search for the ptat the beginning and _kor at the end of the string, and _* matches 0 or more underscores. Note that regex patterns are not the same as wildcards.

In case there can be whitespace between pt_ and _kor, use .*:

preg_match('/\bpt_.*_kor/',$str, $matches);

I should also mention greediness: if you have pt_something_kor_more_kor, the .*/\S* will match the whole string, but .*?/\S*? will match just pt_something_kor. Please adjust according to your requirements.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 I'm glad you modified this answer to explain why the regex is wrong, simply because it's going to be more useful to more people including OP.
1

^ and $ are the start and end of the complete string, not only the matched one. So use simply (pt_.+_kor) to match everything between pt_ and _kor: preg_match('/(pt_+_kor)/',$str, $matches);

Here's a demo: https://regex101.com/r/qL4fW9/1

Comments

1

The ^ and $ that you have used in the regular expression means that the string should start with pt AND end with kor. But it's neither starting as such, nor ending with kor (in fact, ending with kor_7700).

Try removing the ^ and $, and you'll get the match:

preg_match('/pt_.*_kor/',$str, $matches);

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.