Home  >  Article  >  Backend Development  >  How to add "if" to the front of a given string via PHP

How to add "if" to the front of a given string via PHP

藏色散人
藏色散人Original
2021-08-13 09:28:432899browse

hello! Today I will introduce to you how to add "if" to the front of a given string through PHP. Of course, the character "if" is only used as an example. You can also change it to other characters. After all, the process of learning is to master the idea. Below Let’s officially start the central question of this article~

Similarly, I will give a complete question first, so that everyone can think about the implementation method first:

The specific description of the problem is: "How to write A PHP program to create a new string where 'if' is prepended to the front of the given string. If the string already starts with 'if', return the string unchanged"?

Then you can write your own implementation method locally according to the requirements in the question~

The following is a method I provided, you can also refer to:

PHP The code is as follows:

<?php
function test($s)
{
    if (strlen($s) > 2 && substr($s,0, 2) == "if")
    {
        return $s;
    }
    return "if ".$s;
}

echo test("if else")."<br>";
echo test("else");

The output result is:

if else
if else

It is very simple to get it done. It just depends on the mastery of PHP conditional statements, and at the same time, you also need to understand the strlen function and substr function.

strlen() function is used to return the length of a string. substr()The function is used to return a part of a string.

In the example "substr($s,0, 2)", 0 means starting at the first character in the string, 2 means the length of the returned string (the default is until the string end).

So the overall logic is: if the length of $s we give is greater than 2 and the first two characters are equal to if, then $s will be returned directly; otherwise, add it through the . connector Just go to the front of the given string if.

Finally, I would like to recommend the latest and most comprehensive "PHP Video Tutorial"~ Come and learn!

The above is the detailed content of How to add "if" to the front of a given string via PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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