9

I am looking for the regex to stet if a string starts with another string. This has to be RegEx and it has to be PHP regex.

2
  • 1
    Related thread - stackoverflow.com/questions/834303/… Commented Jun 16, 2012 at 5:46
  • 2
    Not really related. Question specifically asks for a "regex" solution. Commented Jun 16, 2012 at 6:52

2 Answers 2

18
$result = preg_match("#^startText(.*)$#i", $string);
if($result == 0)
{
    echo "No match";
}
else
{
    echo "Match found.";
}

PHP.net Regular Expressions

preg_match returns either 0 for no matches found, or 1, because preg_match stops at the first match. If you want to count all matches, use preg_match_all.

Check the PHP website if you have more trouble.

Sign up to request clarification or add additional context in comments.

Comments

1

I'm not sure why you would want to use regex to find a sub-string of a string?.. but here ya go...

/^(?=test).*$/

Usage

<?php

    $string_to_find = 'some_string';
    $search_string = 'some_string_that is longer';

    $regex = '/^(?='.$string_to_find.').*$/';

    // $result variable will be boolean (true|false)
    $result = preg_match($regex, $search_string );

Alternatively

<?php
    function check(){ 
        if(strpos('some_string', 'some_string_that is longer') == 0){ return true; } else { return false; }
    }

Regex Explained Below:

^                   //anchor start matching to first letter

(?=.....)           //look ahead - match exact string value


.*                  //match any leftover characters 0 to infinity x's

$                   //anchor at end of string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.