-3

I have the following string :

abc:def    abc:ghi    abc:jkl

How can I check if my first occurence start with "abc:"? The string has no space except tabulations (\t). This is the result I need :

abc:def    abc:ghi    abc:jkl    // true
foo:def    abc:ghi    abc:jkl    // false
def        abc:ghi    abc:jkl    // false
abc:def    foo:ghi    jkl        // true

Also, i need to check the others parts if needed. For example if i need to check the 2st part :

abc:def    abc:ghi    abc:jkl    // true
foo:def    bar:ghi    abc:jkl    // false
def        ghi        abc:jkl    // false
foo:def    abc:ghi    jkl        // true

I tried preg_match("/abc\:([^\t]+)/",$data,$match); it's worked but this code also return true if the others occurences contains "abc:". Thank you!

EDIT : I'm sorry but this is not a duplicate question. Please see the the second part of my issue. In this second part i'm not requesting how get an element in the first occurence. PHP startsWith() and endsWith() functions has not the solution to this second part of my issue. Thank you.

Community
  • 1
  • 1
DrSAS
  • 396
  • 7
  • 16

3 Answers3

2

You don't need to use regex. PHP has a lot of builtin functions that can search for you.

For first occurrence:

http://php.net/manual/en/function.strpos.php

strpos($data, 'abc') === 0

You can explode each line by "\t" and then check whichever ones you want with the above strpos function.

Schleis
  • 41,516
  • 7
  • 68
  • 87
1

No regex required, you can just use:

   (strpos($string, 'abc') === 0)

It will check that abc is located at the 0 index of the string. (if abc does not exist, it will return -1)

lilwupster
  • 873
  • 9
  • 11
1

First, get the line and explode the string so you have each column in its own bucket.

$line_data = preg_split("/\t/",$line);

Then, pick which column you want and see if it matches what you need.

if (preg_match("/^abc\b/",$line_data[1])){  #This matches the beginning of column 2 only if the string is on a boundary.
    #Do stuff
}
Trenton Trama
  • 4,890
  • 1
  • 22
  • 27