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

Understanding Ruby Classes and Modules

ruby oop class syntax mixins

I have a number of questions regarding ruby classes and modules. I have written a number of test files to kind of explore them further that are too long to post here

Having a custom xml from youtube channel

php youtube youtube-api

I want to show say last 5 videos that I have uploaded in my youtube channel in a block in my site. I currently have this url that produces a xml file.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.