Solved

php search for first occurrence of multiple characters

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

863 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

19 Experts available now in Live!

Get 1:1 Help Now