Solved

php search for first occurrence of multiple characters

Posted on 2012-04-11
2
243 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
  • 2
2 Comments
 
LVL 35

Accepted Solution

by:
Terry Woods earned 500 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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

770 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