?
Solved

php search for first occurrence of multiple characters

Posted on 2012-04-11
2
Medium Priority
?
247 Views
Last Modified: 2012-04-12
Can anybody help?
Thank you

I want a function gives me the position of the  first occurrence any of the elements in $haytack.

eg: Will return position of the comma(,) in $haystack since comma is the first element of the array that occurs in $haystack

$needles= Array ("'",">","<",")",",");
$haystack="test test , ) '  >>><<";
0
Comment
Question by:tyuret
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
2 Comments
 
LVL 35

Accepted Solution

by:
Terry Woods earned 2000 total points
ID: 37835360
function firstNeedlePosition($needles, $haystack) {
  $earliestPosition = 0;
  foreach ($needles as $needle) {
	  $needlePosition = strpos($haystack, $needle);
	  if ($needlePosition and ($earliestPosition==0 or $earliestPosition > $needlePosition))
		  $earliestPosition = $needlePosition;
  }
  return $earliestPosition;
}

Open in new window

0
 
LVL 35

Expert Comment

by:Terry Woods
ID: 37835371
The algorithm I provided will not be efficient if you have very long values of $haystack with the needles first occurring deep within it. In that case, you'd be best to go through the haystack a character at a time looking at whether any of the needles match and stopping at the first match.
0

Featured Post

Are You Using the Best Web Development Editor?

The worlds of web hosting and web development are constantly evolving. Every year we see design trends change, coding standards adapt and new frameworks/CMS created. With such a quick pace of change it’s easy to get lost trying to keep up.

See if your editor made the list.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to create an extensible mechanism for linked drop downs.
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.
Suggested Courses

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question