PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

php怎么反转字符串abcdefg

青灯夜游
青灯夜游 原创
2022-04-14 14:01:39 1542浏览

反转方法:1、用strrev()函数,语法为“strrev("abcdefg")”;2、用for语句和substr(),语法“for($i=字符串长度-1;$i>=0;$i--){$r.=substr("abcdefg",$i,1);}”。

本教程操作环境:windows7系统、PHP7.1版、DELL G3电脑

php反转字符串“abcdefg”

方法1:使用字符串反转函数strrev()

PHP 中提供了大量用来处理字符串的内置函数,例如想要进行字符串反转,就可以使用strrev()函数。

strrev() 函数反转字符串,返回已反转的字符串。

示例:反转字符串“abcdefg”

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$str="abcdefg";
echo "字符串反转前:".$str."<br>";
echo "字符串反转后:".strrev($str);
?>

1.png

方法2:利用for语句、substr()拼接

  • 使用for语句倒序遍历字符串

  • 使用substr()函数从后向前截取一个个字符,并拼接成新字符串

示例:反转字符串“abcdefg”

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$str="abcdefg";
echo "字符串反转前:<br>";
var_dump($str);

$result = &#39;&#39;;
$len = strlen($str);//获取字符串长度
for ($i = $len-1; $i>=0; $i--){
	$result.= substr($str,$i,1);
}
echo "字符串反转后:<br>";
var_dump($result);
?>

2.png

推荐学习:《PHP视频教程

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。