Jump to content

first instance of a letter in a string.


Paul EC1

Recommended Posts

Hi All,

 

I have no idea how to achieve this and your help would be very much appreciated.

 

Firstly,

I am looking to find the first instance of a letter in a string.

 

e.g.

$str = “today is a nice day”

$find = “a”

Result = the first instance of $find  = position 4

 

 

 

And secondly

I am looking to find the secound instance of a letter in a string.

 

e.g.

$str = “today is a nice day”

$find = “a”

Result = the secound instance of $find  = position 10

 

 

Many many thanks

 

Paul

 

Link to comment
https://forums.phpfreaks.com/topic/113642-first-instance-of-a-letter-in-a-string/
Share on other sites

If you want this to work regardless of the case you will need to use strtolower() around $var in the substr() function.

 

<?php

$var = "This is a sentence";
$letter = "e";

// First occurence
echo substr($var, strpos($var, $letter), 1);

// Second occurence
echo substr($var, strpos($var, $letter, strpos($var, $letter)), 1);

?>

try

<?php

function char_positions($needle, $haystack, $caseinsens = 0)
{
    if ($caseinsens)
    {
    	$needle = strtolower($needle);
    	$haystack = strtolower($haystack);
    }
    $arr = str_split($haystack);
    return array_keys($arr, $needle);
}



$str = 'today is a nice day';
$find = 'a';

$positions = char_positions($find, $str);

echo "\"$find\" found at positions " . join (', ', $positions);  //-->   "a" found at positions 3, 9, 17 

?> 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.