How to find the numeric position of the substring with an offset?

if i want to check for an occurance of a string in some text i can use,

strpos($some_string,"word"); this return first char position of the string.

but what if i want to search for the occurance of a string between a set starting point and end point in the text.

so if the $text = "hello my name is fred blogs and i live in a house"

so strpos($text,"fred"); would give about 18

what if i had $text = "hello my name is fred blogs and i live have a brother fred as well and a granda called fred as well"

now i know that the 2nd "fred" in this string lies between positions A & B so do you strpos between these two positions?

Answers


strpos() takes offset as a third argument so you can do:

strpos($text, "fred", 16);

if you know the position of point A and B than you can make use of

strpos(substr($text,POINT A POSITION,POINT B POSITION),"fred");

You can use the 3rd paramater, the offset, to start further in the string. To make it more dynamic:

$string = "fred";
strpos($text, $string, strpos($text, $string)+strlen($string));

This will find the next occurence after the first found. I use the strpos()+strlen() nested as 3rd parameter to make it start with an offset


Need Your Help

Custom CSS security

css security

I'm doing work on a website, and a user can create a custom CSS stylesheet. I understand that there will always be a danger in this, but is there any way that I could make my validation more secure...