Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
PHP preg_replace second occurence of character

How do I adjust my code below to replace the second » character using preg_replace?

$out = 'Home » Food » Fruit';
$out = preg_replace('/»/', 'Category:', $out, 1);

Thanks in advance!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

To only remove the second occurrence of a string, you need to match the first one, and then match and capture all text up to the second one, and then replace using a backreference.

Use

$out = 'Home » Food » Fruit';
$out = preg_replace('/(»[^»]*)»/', '$1Category:', $out, 1);
echo $out;

See the PHP demo. The last $limit argument will have preg_replace only replace the first match.

Details:

  • (»[^»]*) - Capturing group #1 matching
    • » - a literal »
    • [^»]* - 0+ occurrences (due to * quantifier) of any chars other than »
  • » - a literal »

See the regex demo.

A variation that is only supported in Boost/PCRE (and latest versions of Onigmo) and will also work for you:

/»[^»]*\K»/

See another regex demo. \K will discard all the text matched so far in the current iteration. so you will only have the closing chevron in the match to be replaced with your replacement string.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!