Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a pattern of type anystring_OPCtarget_anystring. Can I get some help as how to verify if the string between the 2 underscores is of type "OPC(target)" and pull out the target using regex.

Suppose if my string is: MP700000001_OPC32_812345643 first, I need to verify if the string between underscores starts with OPC and then get the target text after OPC and before the 2nd underscore.

Help appreciated!!!

Thank you


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
925 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use this regex:

^[^_]*_OPCK[^_]+

And grab matched data.

  • ^[^_]*_OPC will match any text upto first _ followed by OPC.
  • K will reset all previously matched data
  • [^_]+ will match data after OPC before 2nd _

RegEx Demo

Code:

$str = 'MP700000001_OPC32_812345643';

preg_match('/^[^_]*_OPCK[^_]+/', $str, $matches);

echo $matches[0] . "
";
//=> 32

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...