Solved

php search for first occurrence of multiple characters

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

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

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

Suggested Solutions

Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
This article discusses how to implement server side field validation and display customized error messages to the client.
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 …

739 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