简体   繁体   English

php正则表达式匹配第一个和最后一个

[英]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.我是正则表达式的新手,想匹配 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 strpos — 查找字符串第一次出现的位置

strrpos — Find position of last occurrence of a char in a string strrpos — 查找字符串中最后一次出现字符的位置

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.贪婪的*量词将注意第一个单词 ( \\w+ ) 和该单词的另一个出现 ( \\1 ,第一个分组的匹配) 之间的字符串尽可能大。

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.在您的情况下, ^charlie匹配第一个样本, charlie$匹配最后一个样本。 Or if you want to match both then it will be ^charlie|charlie$ .或者,如果您想同时匹配两者,那么它将是^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.你想要最后一个,所以它会在位置 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.你必须知道你有多少个名字 [count()] 然后,由于数组从 0 开始计数,你必须减去 1。

$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.祝你好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM