How to prepend a string in PHP? (original) (raw)
Last Updated : 17 Jul, 2024
We have given two strings and the task is to prepend a string **str1 with another string **str2 in PHP. There is no specific function to prepend a string in PHP. To do this task, we have the following operators in PHP:
Below are the methods to prepend a string in PHP
Table of Content
**Method 1: Using Concatenation Operator(".")
The Concatenation operator is used to prepend a string **str1 with another string **str2 by concatenation of **str1 and **str2.
**Syntax: x.x . x.y
**Example :
PHP `
res=res = res=str1 . $str2; // Returning the result return $res; } // Given string $str1 = "Geeksforgeeks"; $str2 = "Example"; // Function Call str=prependstring(str = prepend_string (str=prependstring(str1, $str2); // Printing the result echo $str; ?>`
Output
GeeksforgeeksExample
**Method 2: Using Concatenation assignment operator (".=")
The Concatenation assignment operator is used to prepend a string **str1 with another string **str2 by appending the **str2 to the **str1.
**Syntax: x.=x .= x.=y
**Example :
PHP `
str1.=str1 .= str1.=str2; // Returning the result return $str1; } // Given string $str1 = "Geeksforgeeks"; $str2 = "Example"; // Function call str=prependstring(str = prepend_string (str=prependstring(str1, $str2); // Printing the result echo $str; ?>`
Output
GeeksforgeeksExample
Method 3: Using sprintf()
The sprintf() function formats a string according to a specified format. By specifying a format that includes both strings in the desired order, you can prepend one string with another.
Example
PHP `
result=sprintf(′result = sprintf('%s%s', result=sprintf(′str2, $str1); // Output the result echo $result . "\n"; ?>`