php-regexHow to match strings starting with a certain string using PHP regex?
To match strings starting with a certain string using PHP regex, you can use the preg_match()
function. This function takes two parameters: a regular expression pattern and a string to match against. The pattern should start with a caret (^) followed by the string you want to match. For example, to match strings starting with "Hello":
$string = "Hello World!";
if (preg_match("/^Hello/", $string)) {
echo "String starts with 'Hello'";
}
Output example
String starts with 'Hello'
The code above consists of the following parts:
$string = "Hello World!";
- This assigns the string "Hello World!" to the variable$string
.if (preg_match("/^Hello/", $string)) {
- This uses thepreg_match()
function to check if the string stored in$string
starts with "Hello". The^
character in the regular expression pattern indicates that the string should start with "Hello".echo "String starts with 'Hello'";
- This prints out a message if the string stored in$string
starts with "Hello".}
- This closes theif
statement.
Helpful links
More of Php Regex
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match special characters?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match a word?
- How to use backslash in PHP regex?
- How to use PHP regex to match UUID?
- How to use PHP regex to match UTF8?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match an XML tag?
See more codes...