0

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

1
  • Saying that you want to "access" two literal strings is a little too vague. I mean if you know the strings that you are searching for, you can just use the words that you are searching for (without searching). Do you actually want their offsets in the string? What are you doing with this information? Commented Mar 24, 2021 at 16:44

4 Answers 4

2

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

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

Comments

0

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.

Comments

0

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.

Comments

-1

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.

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.