How to refer to the second occurrence of a string in php? - php

I've been trying to replace my second occurrence for a certain character
For Example:
Hey, I'm trying something With PHP, Is it Working?
I need to get the position of the second comma, I've tried to use strpos but in vain because it's define that it finds the first occurrence of a string so I got Position: 3, any one knows a solution?

The strpos function accepts an optional third parameter which is an offset from which the search for the target string should begin. In this case, you may pass a call to strpos which finds the first index of comma, incremented by one, to find the second comma.
$input = "Hey, I'm trying something With PHP, Is it Working?";
echo strpos($input, ",", strpos($input, ",") + 1); // prints 34
Just for completeness/fun, we could also use a regex substring based approach here, and match the substring up the second comma:
$input = "Hey, I'm trying something With PHP, Is it Working?";
preg_match("/^[^,]*,[^,]*,/", $input, $matches);
echo strlen($matches[0]) - 1; // also prints 34

I know this has been already answered, but a more generic solution to find the last occurrence is to use strrpos.
strrpos accepts a third parameter that can be negative (contrary to strpos).
If negative, the search is performed right to left skipping the last offset bytes of the haystack and searching for the first occurrence of needle.
$foo = "0123456789a123456789b123456789c";
// Looking for '7' right to left from the 5th byte from the end
var_dump(strrpos($foo, '7', -5));

Related

PHP finding "words" within a string

I need to compare 2 lists of strings against each other and output strings which contain the strings searched for. should be very easy, i just can't figure it out.
to overly simplify it, let's use arrays. I am accessing an API with SOAP and running it against my own list contained in a table, but.... let's use arrays. the comparison is what i'm having trouble with.
hit submit button on listsearch.php and it executes.
ARRAY Mylist : TED, DEAD, FIRST, LAST, PUPPY
ARRAY TheirList..<br> teddybearnoose, <br>hauntedhouse, <br>hehasdeparted, <br>deadmouse, <br>walkingdead, <br>thegratefuldead, <br>firstkiss, <br>thinkfirst,<br> firsttobelast,<br> firstmanonthemoon, <br>firstreattempted, <br>somecrap, <br>something, <br>notdisplayed, <br>50000otherwords,<br> miscjunk
outputs as:
TEDdybearnoose<br>
haunTEDhouse<br>
hehasdeparTED<br>
DEADmouse<br>
walkingDEAD<br>
thegratefulDEAD<br>
FIRSTkiss<br>
thinkFIRST<br>
FIRSTtobeLAST <--- note<br>
FIRSTmanonthemoon<br>
FIRSTreattempTED <--- note<br>
<br>
only outputs strings which contain a string in my list, in any position. CAPS is just to make the words stand out to you. not important.
now, part 2?
same "TheirList", except i type a keyword into a text area, and select whether i want it at the beginning end or anywhere from a dropdown.
keywordsearch.php
search for: [ TED ] at: [beginning / end / anywhere] of string.
how would you make that one work?
Thanks in advance. This should be a breeze for most of you. I appreciate it. i'll try to answer questions promptly
You can use strpos() to find the position of a substring (docs).
It makes it very easy to check whether the substring occurred at the beginning or at the end of the string:
// String contains substring
strpos($string, $substring) !== false;
// String starts with substring
strpos($string, $substring) === 0;
// String ends with substring
strpos($string, $substring) === strlen($string) - strlen($substring);

Truncate text to a desired end word

So I want to truncate a very long text but the problem is that I don't want x number of word or characters. I want the text truncated when it reaches a special string like ###end### or something similar e.g. I want to set where exactly it ends.
edit: I know how to check the existences of the string I wasn't sure how to make the truncation
Maybe something like:
$pos = strpos($mystring, "###end###");
$finalText = substr ( $mystring , 0 , $pos );
This can be done with a single call. My answer assumes that the targeted substring will exist in the string.
Code: (Demo)
$string='Here is a sample string.###end### I do not want to see any of this';
echo strstr($string,'###end###',true); // 3rd parameter 'true' will extract everything before
Output:
Here is a sample string.
If you are uncertain if the substring will exist (and if it doesn't, you want the fullstring) this is a reliable method:
Code: (Demo)
$string='Here is a sample string.###end### I do not want to see any of this';
echo explode('###end###',$string,2)[0]; // 3rd parameter 2 will limit the number of elements produced to two
Output:
Here is a sample string.

Find nth character except if its enclosed in brackets php

I use the following function to find the nth character in a string which works well. However there is one exception, lets say its a comma for this purpose, what i need to alter about this is that if the coma is within ( and ) then it shouldnt count that
function strposnth($haystack, $needle, $nth=1, $insenstive=0)
{
//if its case insenstive, convert strings into lower case
if ($insenstive) {
$haystack=strtolower($haystack);
$needle=strtolower($needle);
}
//count number of occurances
$count=substr_count($haystack,$needle);
//first check if the needle exists in the haystack, return false if it does not
//also check if asked nth is within the count, return false if it doesnt
if ($count<1 || $nth > $count) return false;
//run a loop to nth number of occurrence
//start $pos from -1, cause we are adding 1 into it while searching
//so the very first iteration will be 0
for($i=0,$pos=0,$len=0;$i<$nth;$i++)
{
//get the position of needle in haystack
//provide starting point 0 for first time ($pos=0, $len=0)
//provide starting point as position + length of needle for next time
$pos=strpos($haystack,$needle,$pos+$len);
//check the length of needle to specify in strpos
//do this only first time
if ($i==0) $len=strlen($needle);
}
//return the number
return $pos;
}
So ive got the regex working that only captures the comma when outside of () which is:
'/,(?=[^)]*(?:[(]|$))/'
and you can see a live example working here:
http://regex101.com/r/xE4jP8
but im not sure how to make it work within the strpos loop, i know what i need to do, tell it the needle has this regex exception but i am not sure how to make it work. Maybe i should ditch the function and use another method?
Just to mention my end result i want is to split the string after every 6 commas before the next string starts, example:
rttr,ertrret,ertret(yes,no),eteert,ert ert,rtrter,0 rttr,ert(yes,no)rret,ert ret,eteert,ertert,rtrter,1 rttr,ertrret,ert ret,eteert,ertert,rtrter,0 rttr,ertrret,ert ret,eteert,ertert,rtrter,2 rttr,ert(white,black)rret,ert ret,eteert,ertert,rtrter,0 rttr,ertrret,ert ret,eteert,ertert,rtrter,0 rttr,ertrret,ert ret,et(blue,green)eert,ertert,rtrter,1
Note that there is always a 1 digit number (1-3) and a space after the 6th comma before the next part of the string begins but i cant really rely on that as its possible earlier in the string this pattern could happen so i can always rely on the fact ill need to split the string after the first digit and space after the 6th comma. So i want to split the string directly after this.
For example the above string would be split like this:
rttr,ertrret,ertret(yes,no),eteert,ert ert,rtrter,0
rttr,ert(yes,no)rret,ert ret,eteert,ertert,rtrter,1
rttr,ertrret,ert ret,eteert,ertert,rtrter,0
rttr,ertrret,ert ret,eteert,ertert,rtrter,2
rttr,ert(white,black)rret,ert ret,eteert,ertert,rtrter,0
rttr,ertrret,ert ret,eteert,ertert,rtrter,0
rttr,ertrret,ert ret,et(blue,green)eert,ertert,rtrter,1
I can do that myself pretty easily if i know how to get the position of the character then i can use substr to split it but an easier way might be preg_split but im not sure how that would work until i figure this part out
I hope i wasnt too confusing in explaining, i bet i was :)
For these kind of nesting problems regex usually is not the right tool. However, when the problem is actually not that complicated, as yours seems to be, regex will do just fine.
Try this:
(?:^|,)((?:[^,(]*(?:\([^)]*\))?)*)
^ start the search with a comma or the start of the string
^ start non capture group
^ search until comma or open parenthesis
^ if parenthesis found then capture until
^ end of parenthesis
^ end of capture group repeat if necessary
See it in action: http://regex101.com/r/eS0cX4
As you can see this will capture everything between the comma's outside of the parenthesis. If you get all these matches into an array using preg_match_all you can split it any which way you like.

How to find number of occurences of string in comma separated values field

I have a field that contains comma separated values.
I found I can verify the presence in the list of "b" using this code:
SELECT FIND_IN_SET('b','a,b,c,d,b,b')
I want a different thing:
I want to find the number of occurrences of 'b' in that comma separated list. Is this possible in MySQL? Or I must demand it to array_count_values in PHP?
This blog post seems to do what you want:
http://nostylesheets.com/2009/07/17/mysql-substr-count/
Basically, it looks at the string length of the field, removes your target sub-string, then looks at the new length. If you know your substring was 4 characters long, and your new string is now 8 characters shorter than it was, then you know you had 2 occurrences.
LOCATE should do the trick. Note that there are two different signatures - the first (two args) is to be called initially, then call the second (three args), giving the result of the first, as the third argument to the second. More info at:
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_locate
LOCATE(substr,str), LOCATE(substr,str,pos)
The first syntax returns the position of the first occurrence of
substring substr in string str. The second syntax returns the position
of the first occurrence of substring substr in string str, starting at
position pos. Returns 0 if substr is not in str.

How to split a string and find the occurence of one string in another?

I need to figure out how to do some C# code in php, and im not sure exactly how.
so first off i need the Split function, im going to have a string like
"identifier 82asdjka271akshjd18ajjd"
and i need to split the identifier word from the rest. so in C#, i used string.Split(new char{' '}); or something like that (working off the top of my head) and got two strings, the first word, and then the second part.. i understand that the php split function has been deprecated as of PHP 5.3.0.. so thats not an option, what are the alternatives?
and im also looking for a IndexOf function, so if i had the above code again as an example, i would need the location of 271 in the string, so i can generate a substring.
you can use explode for splitting and strpos for finding the index of one string inside another.
$a = "identifier 82asdjka271akshjd18ajjd";
$arr = explode(' ',$a); // split on space..to get an array of size 2.
$pos = strpos($arr[1],'271'); // search for '271' in the 2nd ele of array.
echo $pos; // prints 8

Categories