PHP字符串面试题
1. 创建一个字符串变量,并打印输出字符串的内容。
<?php
$string = "Hello, World!";
echo $string;
?>
2. 如何获取字符串的长度?
<?php
$string = "Hello, World!";
$length = strlen($string);
echo $length;
?>
3. 如何访问字符串中的特定字符?
<?php
$string = "Hello, World!";
echo $string[0];
?>
4. 如何在字符串中查找指定的子串并返回位置?
<?php
$string = "Hello, World!";
$position = strpos($string, "World");
echo $position;
?>
5. 如何将字符串转换为大写或小写?
<?php
$string = "Hello, World!";
$uppercase = strtoupper($string);
$lowercase = strtolower($string);
echo $uppercase;
echo $lowercase;
?>
6. 如何截取字符串的一部分?
<?php
$string = "Hello, World!";
$substring = substr($string, 0, 5);
echo $substring;
?>
7. 如何替换字符串中的指定子串?
<?php
$string = "Hello, World!";
$newString = str_replace("World", "PHP", $string);
echo $newString;
?>
8. 如何去除字符串两端的空格?
<?php
$string = " Hello, World! ";
$trimmedString = trim($string);
echo $trimmedString;
?>
9. 如何将字符串拆分为数组?
<?php
$string = "apple,banana,orange";
$array = explode(",", $string);
print_r($array);
?>
10. 如何将数组的元素连接成一个字符串?
<?php
$array = array("apple", "banana", "orange");
$string = implode(", ", $array);
echo $string;
?>