Php String Examples string addslashes ( string str ) adds more and more slashes chdir() function changes to the file directory. chop() function returns a string minus any ending whitespace and newlines. string chr ( int ascii_val ) converts an ASCII number to its character equivalent count_chars.php mixed count_chars ( string str [, int mode] ) returns an array containing the letters used in that string and how many times each letter was used. Fetching a URL with cURL Writing a response body to a file with cURL A regular expression for e-mail string checking Validate email Use regular to check email address Capturing Text Inside HTML or XML Tags Displaying elements of $regs array Filling Patterns with ereg ereg() function searches a string, returning true if the pattern is found, and false otherwise. ereg.php break $url down into three distinct pieces Case-insensitive Pattern Matching Getting the title of a remote page eregi() function searches a string for another string. eregi.php back-reference parenthesized substrings ereg_replace ereg_replace() function searches for string and replaces pattern if found. ereg_replace-2 ereg_replace.php Using ereg_replace An alternative to base_convert() Concatenation with a here document Interpolating in a here document Defining a here document More here documents Printing HTML with a here document Implementing Custom Type Hinting Comparing Phrases ltrim() function removes the whitespace and special characters from the left side of string ltrim() function to strip white space only from the beginning of a string. Left padding using the default of spaces metaphone functionnl2brint ord ( string str ) returns the equivalent ASCII value preg_grep preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern. Using preg_grep() Quickly finding lines that match a pattern Capturing with nested parentheses Capturing with preg_match() Check quotes in a file Combine patterns with the pipe (|) character to create branches Checking the syntax of an e-mail address preg_match preg_match( ) calls and what they match preg_match() function returns true if pattern exists, and false otherwise. Matching Patterns with preg_match() Matching with preg_match() PREG_OFFSET_CAPTURE and preg_match() Using preg_match to return an array of matches that start with ple Detecting ZIP Codes in Strings Looking for any lowercase alphabetical character or the numbers 3, 4, and 7 Efficiently finding lines that match a pattern Find the first "p" string and match as many characters as possible until the last possible "t" is reached. Finding All Matching Lines in a File Finding Lines with an Odd Number of Quotes Finding Repeated Words Finding Words Not Followed by Other Words Finding the nth Occurrence of a Match Get the start and end of the string when m is enabled, you should use \A and \z, like thisNegate the characters in the character class Parsing a date with a regular expression Words and Whitespace Regexps i renders the regular expression non case sensitive s modifierRegular expressions using +, *, and ? Regular expressions using braces Put the word boundary character to the test Validating numbers with regular expressions Use regular expression to check each line of the code Testing the Complexity of Passwords A non-capturing optional subpattern Capturing HTML headings preg_match_all preg_match_all demo preg_match_all searches a string for all the occurrences of a regular expression preg_match_all() function matches all occurrences of pattern in string. Finding Matches Globally with preg_match_all() Matching with preg_match_all() Using preg_match_all() to Match a Pattern Globally Using preg functions Extracting text from HTML tags Finding the nth match Making a quantifier match as few characters as possible m modifierReading Records with a Delimiter preg_quote $0 is set to the whole match, then $1, $2 Converting Line Breaks preg_replace preg_replace with index Pass a fourth parameter to preg_replace( ) to specify the maximum number of replacements you want to make. Pass arrays of regular expressions and replacement strings to preg_replace(). Replacing with preg_replace() Using Back References with preg_replace() Using preg_replace() to Replace Patterns e modifier treats the replacement string in preg_replace() as if it were PHP. pass arrays as parameter one and parameter two, and preg_replace() performs multiple replaces Escape a character in HTML Replacing URLs with Links Formatting a Phone Number Entity encoding matched text Escaping Special Characters Regular Expression Replacements Remove any doubled-up whitespace Replace any non-space whitespace, with a space Replace with regular expression Replacing using backreferences Quote escaping in backreference replacements Using preg_replace_callback() to Replace Patterns Generating replacement strings with a callback function Generating replacement strings with an anonymous function Calculating average word length preg_split() Flags preg_split() function operates like split(), except that regular expressions are accepted as input parameters for pattern. preg_split.php Discarding empty elements with preg_split() How preg_split() can be usedLimiting the number of returned elements with preg_split() Parsing a date with preg_split() Using preg_split() Using preg_split() to Break Up Strings Double quotation marks allow the parsing of variables Double-quoted string escape sequences Double-quoted strings If you use single quotation marks to enclose the same string, the variable is not substitutedUsing forward slashes on Windows Fixing quote escaping in backreference replacements It is safe to use non-escaped Windows-style filenames in your single-quoted strings Various special characters in string assignments Brackets [] finds a range of characters. Character Classes Complete list of regular expression examples \b and \B, equate to "On a word boundary" and "Not on a word boundary," respectively. ^ and $ are line anchors. Line Anchors Match URL Match an IP address Match the smallest number of characters starting with "p" and ending with "t" Matching GUIDs/UUIDs Matching a Valid E-mail Address Matching a Valid IP Address Matching using backreferences Matching with Greedy vs. Nongreedy Expressions Matching with character classes and anchors Matching with | Define a pattern and use parentheses to match individual elements within it Greedy Qualifiers Greedy and non-greedy matching Greedy versus nongreedy matching Grouping captured subpatterns Validating Pascal Case Names Validating U.S. Currency Validating a credit card number Nongreedy Qualifiers POSIX Regular Expressions Character Classes Ranges Option patternsPredefined Character Ranges (Character Classes) Pattern matchesPattern match extendersPerl-Compatible Regular Expressions (PCRE) Qualifiers restrict the number of times the preceding expression may appear. Quantifiers for Matching a Recurring Character QuantifiersSpecial classes for regular expression Regular expressions using character classes the m modifier to change the behavior of $ preg_replaceCleaning Up a String with trim(), Itrim(), and strip_tags() string rtrim ( string str [, string trim_chars] ) only trims whitespace from the righthand side of a string. Checking for Similar Names Determine the similarity between two strings is provided by the similar_text function Comparing Sound Comparing SoundThe soundex algorithm is implemented in PHP through the soundex function Generating date-based drop-down menu options split() function divides a string into various elements. split.php Use split() to limit a parameter to restrict division of $ip Using a sprintf()-style message catalog Using sprintf with a variable Using sprintf() to ensure that one digit hex numbers (like 0) get padded with a leading 0. sprintf print values to a string sprintf()'s built-in hex-to-decimal conversion with the %x format character Integral that the value be displayed as a dollar amount set to two decimal placesinteger displayed as a dollar amount set to two decimal places Storing a Formatted String Wrap these in a couple of functions and surround the joined array elements with parentheses Comparing strings case-insensitively strcasecmp() function operates like strcmp(), except that its comparison is case insensitive. Using strcasecmp to compare two strings int strcasecmp ( string str1, string str2 ) is a case-insensitive version of the strcmp( ) . Comparing strings Comparing strings with strcmp() strcmp() function performs a case-sensitive comparison of two strings. int strcmp ( string str1, string str2 ), case-insensitive sibling, strcasecmp( ) For example, using my collation rules (Canadian-English), I obtain the following resultsstrcspn($password, '1234567890') strspnstrcspn demo See what portion of a string is composed only of a given set of characters ucwords() function capitalizes the first letter of each word in a string. Change String case to lower Initial-capping words is a very common task Change String case to Upper Trimming StringsString compare demoString comparestrcasecmpString compare with if statement Compare string A period (.) character is used to combine two separate variables into a single string A string and an integer value are added, and the result is an integer value. Combining a string and a number Concatenating strings together Concatenation operator ('.') Joining and Disassembling Strings String contains string String word count String word count and frequency To embed a single quote in a singly quoted string, escape it with a backslash addslashes()quotemeta()String SQL command escape Finding a Substring Within a String with strstr() String find Demo Adding "s" to the end of the variable name Embed variables directly into strings Embedded Conditionals Embedding numbers and strings into other strings Interpolating with curly braces Limit string length and display '...' Finding the Length of a String with strlen() String match for domain name A simple use of preg_match() String matchesString match demoString match demo$String matchesString match and if statement String Operators summary table String Concatenation Operators Pad a string to a certain length with another string str_padString Repeat Demo Quantifier Syntaxes str_replaceReplacing a Pattern with a Found String Replace the tag content without getting rid of any attributes String replace with Regular Expressions What happens when multiple instances of the search string overlap? String replacepreg_split (/\+{1,}/) Splitting a String Based on a Found String Use more than one delimiter to split string String token for string split String tokenString string token value Dividing a String into Tokens with strtok() Trim only tab and newline characters from $str Trimming StringsTrimming StringsTrimming Strings for 'tab' and 'return' Specify the characters in charlist by giving their hexadecimal value String trim chop and length Check string password Combine an expression with a string Comparing strings with the equality operator An Escape PHP 5 Substring Functions Escape Characters That Act As Anchors Escape Characters in PHP Escape sequences and their meanings (continued) Indexing Strings Getting an individual byte in a string curly offset syntax Processing each byte in a string Some string examples Using {x} notation with strings to read or write individual characters Using Escaped Characters Supported String Delimiters string stripslashes ( string str ) is the opposite of addslashes( )strip_tags strip_tags() function removes all HTML and PHP tags from string, leaving only the text entities. strip_tags() function, first argument is the text to transform. strip_tags.php string strip_tags ( string html_text [, string allowed_tags] ) strips HTML and PHP tags from a string Stripping HTML tags from a string Strip all except a few tags Using Substring Alternatives Detecting whether a string is contained in another string Calculating the length of a string Checking String Length Checking String LengthConcisely checking the length of a trimmed string strlen.php int strlen ( string str ) returns the number of characters in itstrrpos() function locates the last occurrence of character in string. strrpos.php Using several functions together to extract a portion of a string A third parameter to strpos( ) that allows us to specify where to start searching from Finding a substring with strpos() Finding the Position of a Substring with strpos() int strpos ( string haystack, mixed needle [, int offset] ) returns the index of the beginning of a substring's first occurrence within a string strpos( ) will return false (as opposed to -1) strpos() function finds the position of the first occurrence in string. Return String found at position 22 Using String Matching vs. Pattern Matching Reversing StringsReversing a string by byte Truncating Text on Word Boundaries Reversing Strings strpos strspn() function returns the length of the first segment in string1 containing characters also in string2. strspn.php strcspn() function returns the length of the first segment in string1 containing characters not in string2. string strstr ( string haystack, string needle ) finds the first occurrence of a substring inside another string (parameter one) strstr function demo strstr() function returns the remainder of string beginning at the first occurrence. strtr() function converts all characters contained in destination to their corresponding character matches in source. strtr.php strtok() function performs a similar task to explode() strtok() function tokenizes string, using the characters specified in tokens. strtok.php Changing case Controlling Casestring strtolower ( string str ) returns that string entirely in lowercase characters. strtolower() function converts a string to all lowercase letters. strtolower.php Calculating a date interval with strtotime() Checking a date range int strtotime ( string time [, int now] ) converts strings to a timestamp Using strtotime() Using strtotime() with a starting epoch timestamp Find the First monday on or after November 1, 2008 Find weekday Finding the Date for a Weekday Getting the Day and Week of the Year If PHP is unable to convert your string into a timestamp, it will return -1. Obtaining the Difference Between Two Dates Subtracts a year from a given timestamp Changing case of strings Converting Case string strtoupper ( string str ) returns that string entirely in uppercase characters. strtoupper()strtoupper.php Modifying capitalize( ) to take a reference parameter Using the word case functions Checking for an integer Validating an integer with typecasting Case-insensitive version of str_replace( )Implementing a phrase-substitution algorithm str_pad() function pads string to length pad_length with a specified characters str_pad-2.php str_pad.php string str_pad ( string input, int length [, string padding [, int type]] ) Make use of str_pad()'s optional parameters STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTHThere is an optional third parameter to str_pad( ) that lets you set the padding character to use Using left space padding Using left zero padding Replacing Substrings Using str_replace() str_replace demo str_replace() accepts arrays for all its arguments str_replace() function searches for occurrence in string, replacing all instances with replacement. str_replace.php Using str_replace() mixed str_replace ( mixed needle, mixed replace, mixed haystack [, int &count] ) Replacing Tabs with Spaces case-sensitive? Using template file Switching tabs and spaces array str_split ( string string [, int split_length] ) str_word_count-2.php str_word_count.php mixed str_word_count ( string str [, int count_type [, string char_list]] ) returns the number of words in a string Substring replace Substring count substr($string, 3) substr($String, 3, 5) substr($String, -3, 5) (2) substr($String, -3, -5) (3) substr($String, 3, -5) (4) Extracting Part of a String with substr() A negative substr() length parameter A positive substr() length parameter Accessing SubstringsExtracting a substring with substr() Extracting the end of a string with substr() If you pass substr() a negative number, it counts from the end of the string. Setting up and working with both strings and substrings Single-character substitutions Truncating a string with substr() Using substr() with length past the end of the string Using substr() with negative length Using substr() with negative start Using substr() with positive $start and $length Using substr() with positive start and no length string substr ( string str, int start_pos [, int length] ) reads part of a string and takes a minimum of two parameters substr() function returns the part of the string between the start and start+length parameters. substr-2.php substr-3.php substr.php Specify a negative number as parameter three for the length Using negative lengths allows you to say "copy everything but the last three characters," Reading Fixed-Width Delimited Data Counting the Occurrences of a Substring Testing for Substrings substr_count() function returns the number of times substring occurs in string. substr_count.php By supplying no start or length arguments, the string will be added to the beginning PHP has two main functions for performing simple search-and-replace operations. The first one is substr_replace Replacing SubstringsReplacing a Portion of a String Using substr_replace() Replacing a substring with substr_replace() substr_replace() function replaces the string with replacement. substr_replace.php Checking the length of a trimmed string Combining trim() and strlen() string trim ( string str [, string trim_chars] ) strips spaces, new lines, and tabs trim() function removes all whitespace from both sides of string Capitalizing letters ucfirst() function capitalizes the first letter of a string. ucfirst.php string ucfirst ( string str ) converts the first letter of the string to an uppercase character Controlling Case ucwords() makes the first letter of every word in a string uppercase. ucwords.php string ucwords ( string str ) converts the first letter of each word in the string to an uppercase character, leaving the others untouched. submitted string lowercase with strtolower() before invoking ucwords()Prettifying names with ucwords() wordwrap() doesn't break at your line limit if a word has more characters than the limit. wordwrap() has two more optional argumentswordwrap() requires one argument, the string to be transformed. string wordwrap ( string str [, int line_length[, string break_char [, bool cut]]] ) string wordwrap ( string str [, int width [, string break [, bool cut]]] ) Wrapping Text Supply 1 as a fourth parameter, which enables "cut" modewords over the limit will be cut up if this is enabled.

Php Code : M Modifier

m modifier in php

The anchor patterns ^ and $ match the beginning and end of an entire string by default. 

$text = "name: Joe\noccupation: coder\n\n";
if ( preg_match_all( "/^\w+:\s+(.*)$/m", $text, $array ) ) {
  print "<pre>\n";
  print_r( $array );
  print "</pre>\n";