开发者

php regex matching first and last

i'm new to regular expressions and would like to match the first and last occurrences of a term in php. for instance in this line:

"charlie, mary,bob,bob,mary, charlie, charlie开发者_高级运维, mary,bob,bob,mary,charlie"

i would like to just access the first and last "charlie", but not the two in the middle. how would i just match on the first and last occurrence of a term?

thanks


If you know what substring you're looking for (ie. it's not a regex pattern), and you're just looking for the positions of your substrings, you could just simply use these:

strpos — Find position of first occurrence of a string

strrpos — Find position of last occurrence of a char in a string


Try this regular expression:

^(\w+),.*\1

The greedy * quantifier will take care that the string between the first word (\w+) and another occurrence of that word (\1, match of the first grouping) is as large as possible.


You need to add ^ and $ symbols to your regular expression.

  • ^ - matches start of the string
  • $ - matches end of the string

In your case it will be ^charlie to match first sample and charlie$ to match last sample. Or if you want to match both then it will be ^charlie|charlie$.

See also Start of String and End of String Anchors for more details about these symbols.


Try exploding the string.

$names = "charlie, mary,bob,bob,mary, charlie, charlie, mary,bob,bob,mary,charlie";
$names_array = explode(",", $names);

After doing this, you've got an array with the names. You want the last, so it will be at position 0.

$first = $names_array[0];

It gets a little trickier with the last. You have to know how many names you have [count()] and then, since the array starts counting from 0, you'll have to substract one.

$last = $names_array[count($names_array)-1];

I know it may not be the best answer possible, nor the most effective, but I think it's how you really start getting programming, by solving smaller problems.

Good luck.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜