How to check if a string starts with "_" in PHP?
In PHP, you can use the substr()
function to check if a string starts with a specific character or substring. For example, to check if a string starts with an underscore (_), you can use the following code:
<?php
$string = '_example';
if (substr($string, 0, 1) == '_') {
echo 'The string starts with an underscore.';
} else {
echo 'The string does not start with an underscore.';
}
Watch a video course
Learn object oriented PHP
Another way to check this is by using the built-in function strpos()
<?php
$string = '_example';
if (strpos($string, '_') === 0) {
echo 'The string starts with an underscore.';
} else {
echo 'The string does not start with an underscore.';
}
You can also use the str_starts_with()
function if it's available in your version of PHP.
<?php
$string = '_example';
if (str_starts_with($string, '_')) {
echo 'The string starts with an underscore.';
} else {
echo 'The string does not start with an underscore.';
}
All of the above will return 'The string starts with an underscore.'