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
-
1Related thread - stackoverflow.com/questions/834303/…KV Prajapati– KV Prajapati2012-06-16 05:46:18 +00:00Commented Jun 16, 2012 at 5:46
-
2Not really related. Question specifically asks for a "regex" solution.Slappy– Slappy2012-06-16 06:52:40 +00:00Commented Jun 16, 2012 at 6:52
Add a comment
|
2 Answers
$result = preg_match("#^startText(.*)$#i", $string);
if($result == 0)
{
echo "No match";
}
else
{
echo "Match found.";
}
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.
Comments
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