Solved

php search for first occurrence of multiple characters

Posted on 2012-04-11
2
241 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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
This article discusses how to create an extensible mechanism for linked drop downs.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
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 …

760 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now