开发者

Getting matching text & number in PHP

开发者 https://www.devze.com 2023-02-17 12:39 出处:网络
I need to be able to get a matching combination from a string. Example: $mystring = \"This is my text00123 blah blah\";

I need to be able to get a matching combination from a string. Example:

$mystring = "This is my text00123 blah blah";
$code = magicRegex( $mystring, "text"[0-9] );
return "you are a wiza开发者_Python百科rd - your code is " . $code;

Return:

you are a wizard - your code is text00123

Then, I need to separate the text from the integers into separate variables.


As another alternative, named catching:

\b(?<text>\w+?)(?<number>\d+)\b

Demo:

$str = "This is my text00123 blah blah";

$_ = null;
preg_match("/\b(?<text>\w+?)(?<number>\d+)\b/",$str,$_);
echo "Text: {$_[text]} -- Number: {$_[number]}";

Working Demo

Oops, reversed the arguments. ;p


This should do it:

preg_match("text[0-9]+", $mystring, $matches);
$code = $matches[0];

To split the string you could use lookahead and lookbehind:

list($text, $number) = preg_split('/(?<=[a-z])(?=\d)/', $code);


Use preg_match() to do the job. The right pattern would most likely be "/(text[0-9]+)/" assuming you'd like at least 1 number.


for the first one, you can do

$code = preg_replace("/.*(text[0-9]*).*/", "$1", $mystring);
0

精彩评论

暂无评论...
验证码 换一张
取 消