简体   繁体   中英

Regex - Echoing the first character of a string

I try to echo the first letter of "SiteName", I am having a bit of difficulties, the expression below returns "1" instead of "S".

// $sitename = $GLOBALS["AL_CFG"]["siteName"];

$sitename = "SiteName.com";
$sitename1 = preg_match("/.{0,1}/", $sitename);
echo $sitename1;

Thank you for your help.

That's because preg_match() returns a value indicating whether the match succeeded or not, and not the actual match itself. To access the matches, you need to specify the third argument, an array, in which you would like to have the matches stored:

$sitename1 = preg_match("/.{0,1}/", $sitename, $matches);
print_r($matches);
echo $matches[0]; // => 'S'

Anyway, if you're just trying to get the first character of a given string, you don't need to use regex at all ; you can simply access the string as a character array:

From the PHP docs :

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42] . Think of a string as an array of characters for this purpose. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character.

So to get the first charcter from $sitename , you would write:

echo $sitename[0]; // => 'S'

If you are only trying to capture the first character in a string, then you do not need to use a regular expression.

$sitename = "SiteName.com";
$letter = substr($sitename, 0, 1);
echo $letter; // prints "S"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM