Home > Backend Development > PHP Tutorial > php character reverse

php character reverse

WBOY
Release: 2016-07-29 09:13:30
Original
915 people have browsed it

1. Use php’s built-in functions to implement
Test code

<code><span><span><?php</span><span>$str</span>=<span>'Hello World!'</span>;
<span>$res</span>=strrev(<span>$str</span>);
<span>echo</span><span>$res</span>.<span>'</br>'</span>;
<span>$str</span>=<span>'Hello World!你好 世界!'</span>;
<span>$res</span>=reverse(<span>$str</span>);
<span>echo</span><span>$res</span>;

<span>//自定义函数</span><span><span>function</span><span>reverse</span><span>(<span>$str</span>)</span> {</span><span>$len</span> = mb_strlen(<span>$str</span>, <span>'utf-8'</span>);
    <span>for</span> (<span>$i</span> = <span>0</span>; <span>$i</span> < <span>$len</span>; <span>$i</span>++) {
        <span>$arr</span>[] = mb_substr(<span>$str</span>, <span>$i</span>, <span>1</span>, <span>"utf-8"</span>);
    }
    <span>return</span> implode(<span>""</span>, array_reverse(<span>$arr</span>));
}
<span>?></span></code>
Copy after login

Run results
!dlroW olleH!
Hello Jishi!dlroW olleH

2.C language implementation

<code><span>#<strong>include</strong> <stdio.h></span><span>#<strong>include</strong><string.h></span><span>char</span> *<span>str</span>=<span>"Hello World!你好 世界!"</span>;

<span>int</span> main() {
  <span>int</span> i = strlen(<span>str</span>) - <span>1</span>;
  <span>while</span> (i>=<span>0</span>) {

        <span>if</span>(<span>str</span>[i] < <span>0</span>)
        {
                printf(<span>"%c%c%c\n"</span>, <span>str</span>[i-<span>2</span>], <span>str</span>[i-<span>1</span>],<span>str</span>[i]);
                i = i-<span>2</span>;
        }<span>else</span>{
                printf(<span>"%c\n"</span>, <span>str</span>[i]);
        }
        i--;
  }
  <span>return</span><span>0</span>;
}</code>
Copy after login
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

The above introduces PHP character reversal, including include content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template