Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find the second occurrence of a char in a string php

Tags:

string

php

Imagine i have this string :

$info="portugal,alemanha,belgica,porto 1-0 alemanha, belgica 2-0";

I want to know the position of the 2nd char "-", so i want the result 2-0 and not the result 1-0.

I'm using this function, but it's always returning the first position,

$pos = strpos($info, '-');

Any idea? Thanks

like image 404
unpix Avatar asked Nov 21 '12 11:11

unpix


People also ask

Where is second occurrence of a character in a string PHP?

Simplest solution for this specific case is to use the offset parameter: $pos = strpos($info, '-', strpos($info, '-') + 1);

What is the use of strpos () function in PHP?

strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.

How do I check if a string contains a specific character in PHP?

Answer: Use the PHP strpos() Function You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .

How do I count the number of repeated characters in a string in PHP?

php $string = "learnetutorials.com"; $string = strtolower($string); $size = strlen($string); echo "The entered string is : $string \n"; echo "The duplicate characters in the string are: \n"; for ($i = 0; $i < $size; $i++) { $count = 1; for ($j = $i + 1; $j < $size; $j++) { if ($string[$i] == $string[$j] && $string[$i] ...


2 Answers

Simplest solution for this specific case is to use the offset parameter:

$pos = strpos($info, '-', strpos($info, '-') + 1);

You might want to look into using regular expressions, though.

like image 113
Rijk Avatar answered Oct 02 '22 04:10

Rijk


Try this

preg_match_all('/-/', $info,$matches, PREG_OFFSET_CAPTURE);  
echo $matches[0][1][1];
like image 39
user1835851 Avatar answered Oct 02 '22 03:10

user1835851