Philemon philip Kunjumon
Philemon philip Kunjumon

Reputation: 1422

How can I check if a certain string is at the start of a string?

I am trying to preg_match a string .basically if i got a string which is given to a variable

$line = " <szFilename> &#6; ds  </szFilename>  "

And I need to check if the sting starts with "<szFilename>" . am finding a hard time finding the pattern. What i tried is

$line=" <szFilename> &#6; ds  </szFilename>  ";
//$line2=" <szFilenamed1> &#6; ds  </szFilenamed1>  ";
//echo trim($line);
if(preg_match("/[<szFilename>]*/",trim($line))){
    echo "GOT IT";
 }

Any help?

Upvotes: 0

Views: 46

Answers (2)

Rizier123
Rizier123

Reputation: 59681

No need for a regex here. Just simply use strpos() to determinate if the string is at the start (index 0) or not, e.g.

if(strpos(trim($line), "<szFilename>") === 0) {
    echo "success";
}

If you want/need to use a regex, just use an anchor (^) to match your regex at the start, e.g.

if(preg_match("/^<szFilename>/", trim($line))) {
    echo "success";
}

Also if you are writing your own regex's, I can highly recommend this site: https://regex101.com/, which highlights everything nicely and you get an nice explanation to the right, what your regex does.

Upvotes: 4

Flosculus
Flosculus

Reputation: 6946

Just '/^\s*<szFilename>.+/' is all you need.

Upvotes: 2

Related Questions