2

I'm having trouble knowing how many times that the - character is in front of my string.

Some examples:

$string = "-Lorem Ipsum";   // 1
$string = "--Lorem Ipsum";  // 2
$string = "---Lorem Ipsum"; // 3
$string = "--Lorem-Ipsum";  // 2

But how can I find this? I know you can search the number of occurrences of a character in a string. But I want the number of - characters before an alphabet letter. Not all the sequences (see last example).

How should I approach this?

nielsv
  • 6,540
  • 35
  • 111
  • 215

3 Answers3

3

You can use the old school trick of using a string as an array here as such:

$search="-";
$i=0;
while($string[$i]==$search)
{
    $i++;
}
echo "Found $i instances at the start of the string.";
Fluffeh
  • 33,228
  • 16
  • 67
  • 80
1

What about using ltrim() and strlen()

echo strlen($string) - strlen(ltrim($string, "-"));

See example at eval.in

Jonny 5
  • 12,171
  • 2
  • 25
  • 42
0

it would also work -

preg_match('/(?!-)/', $string, $match, PREG_OFFSET_CAPTURE);

$match - the position of any character but - which is indeed the count of -.

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87