|
|
|---|
String Manipulation in PHPIn this section, we will learn different ways of manipulating string through PHP coding. Some of these are basic coding techniques while some will require using built-in functions of PHP for advance string manipulation. String ConcatenationOne of the most simplest string manipulation activity that can be done is concatenating two or more strings to form a single string. For example: $a might hold a string called "First" and $b might hold a string called "Second". To concatenate these two strings into one, we use a '.' (dot). See this example:
<?phpChange the case of a string to lowercase and UPPERCASEThat's quite easy! All we need to do is use the built-in function called strtolower() to convert a string to lowercase and strtoupper() for uppercase conversions. See the example to convert a string to lowercase and uppercase.
<?phpNow, use the above example but replace the used functions with ucwords() (Uppercase the first character of each word in the string) and also ucfirst(). Determining position of first occurrence of a stringThis is easy one! We will use yet another handy built-in function called strpos(). The syntax of strpos() is:
strpos ( string, keyword [, int offset] )
This will return 'FALSE' if the keyword is not found in the string and you will have to use '===' (strict comparison) to check the returned value. See the below example for usage of strpos().
<?phpReturn portion of a string from a given stringTo get portion of a string from a given string we will make use of substr() function of PHP. The syntax is:
substr ( string , int start [, int length] )
Remember, the position of the first character of the string is always '0'. The function will take the start position and return a portion of the string from the start position as specified. You may optionally also mention the end position till which you want to get the portion of any given string. For example, in the string "Hello", the letter 'H' is at position '0' and the letter 'o' is at position '4'. See this example:
<?phpAdding slashes to stringUnder various circumstances, you will need to automatically add slashes to escape special characters in a string. Be it storing in database table, or for anything else. Here's how we can do it with built-in addslashes() function. The syntax is:
addslashes ( string )
Below is an example to add slashes to any given string.
<?phpThat's all folks! We will later on add more examples here. You may visit the examples section for other examples. With this section, we have completed our session on Strings in PHP. If you want to see more detailed information on this section, please contact us and let us know. |
|
|
|---|