Reading a file in PHP. We choose the best option. PHP: working with strings. PHP string functions Php string parsing

Strings are a very important data type that you have to constantly work with when solving web development problems. This article describes 10 very useful techniques that will make the life of a PHP developer easier.

Automatically removing html tags from a string

When using user-filled forms, sometimes you need to remove all unnecessary tags. This task easily solved using the strip_tags() function:

$text = strip_tags($input, "");

Getting the text between $start and $end

Such a function should be in the developer's arsenal: it receives the original line, the beginning and end, and returns the text that is contained between $start and $end.

Function GetBetween($content,$start,$end)( $r = explode($start, $content); if (isset($r))( $r = explode($end, $r); return $r; ) return "" )

Transforming a URL into a hyperlink

If you put the URL in comment form in WordPress blog, it will automatically transform into a hyperlink. If you want to implement the same functionality on your website or web application, you can use the following code:

$url = "Jean-Baptiste Jung (http://www.webdevcat.com)"; $url = preg_replace("#http://(+)#", " ", $url);

Splitting text into a 140 character array for Twitter

Maybe you know that Twitter accepts messages no longer than 140 characters. If you have plans to interface your app with a popular social messaging site, then a feature that trims messages to 140 characters will probably be a good fit.

Function split_to_chunks($to,$text)( $total_length = (140 - strlen($to)); $text_arr = explode(" ",$text); $i=0; $message=""; foreach ($text_arr as $word)( if (strlen($message[$i] . $word . " ")<= $total_length){ if ($text_arr == $word){ $message[$i] .= $word; } else { $message[$i] .= $word . " "; } } else { $i++; if ($text_arr == $word){ $message[$i] = $word; } else { $message[$i] = $word . " "; } } } return $message; }

Removing the URL from the string

Many people leave URLs in blog comments to get traffic or generate feedback. Such links pollute the blog and can cause frustration for the owner if there are a large number of them. So the next feature will be very useful!

$string = preg_replace("/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*/ i", "", $string);

Converting a string to a slug

Need to generate a slug (for a permalink) that is compatible with SEO goals? The following function takes a string as a parameter and returns an SEO-compatible slug. Simple and effective!

Function slug($str)( $str = strtolower(trim($str)); $str = preg_replace("/[^a-z0-9-]/", "-", $str); $str = preg_replace ("/-+/", "-", $str); return $str;

Parsing a CSV file

CSV (Coma separated values) files are a simple way to store and transfer data, and parsing such files in PHP is extremely easy. Don't believe me? The following code demonstrates processing a CSV file:

$fh = fopen("contacts.csv", "r"); while($line = fgetcsv($fh, 1000, ",")) ( echo "Contact: ($line)"; )

Finding a string in another string

If a string is contained in another string and you need to find it, then the problem is simple:

Function contains($str, $content, $ignorecase=true)( if ($ignorecase)( $str = strtolower($str); $content = strtolower($content); ) return strpos($content,$str) ? true: false)

Checking that a string starts with a certain pattern

Some programming languages, such as Java, have a startWith method/function that allows you to check whether a string starts with a certain pattern. Unfortunately, PHP doesn't have such a simple built-in function.
However, we can do it for ourselves, and very simply::

Function String_Begins_With($needle, $haystack) ( return (substr($haystack, 0, strlen($needle))==$needle); )

We highlight email from string

Ever wondered how spammers get your email addresses? It's simple. They take a web page (for example, from a forum) and parse the html code to extract email addresses. The code below takes a string as a parameter and prints all the emails contained in it. Please do not use this code for spam!

Function extract_emails($str)( // Regular expression that extracts all emails from a string: $regexp = "/()+\@(()+\.)+((2,4))+/i"; preg_match_all ($regexp, $str, $m); return isset($m) ? $m : array(); ) $test_string = "Test string... [email protected] Checking other formats: [email protected]; foobar Another check: [email protected] test6example.org [email protected] test8@ example.org test9@!foo!.org foobar "; print_r(extract_emails($test_string));

Inserts HTML line break code before each line feed

  • number_format - Formats a number with group separation
  • ord - Returns the ASCII code of a character
  • parse_str - Parses a string into variables
  • print - Prints a string
  • printf
  • quoted_printable_decode - Decodes a string encoded by the quoted printable method
  • quotemeta - Escapes special characters
  • rtrim - Removes spaces from the end of a string
  • sha1 - Returns the SHA1 hash of a string
  • sha1_file - Returns the SHA1 hash of a file
  • similar_text - Calculates the degree to which two strings are similar
  • soundex - Returns the soundex key for a string
  • sprintf
  • sscanf - Parses a string according to a given format
  • strcasecmp - Case-insensitive string comparison that is binary safe
  • strcmp - Binary-safe string comparison
  • strcoll - Compare strings based on the current locale
  • strcspn - Returns the length of the portion at the beginning of the string that does not match the mask
  • stripcslashes - Removes character escaping produced by the addcslashes() function
  • stripos - Returns the position of the first occurrence of a substring, case insensitive
  • stripslashes - Removes character escaping produced by addslashes()
  • strip_tags - Removes HTML and PHP tags from a string
  • stristr - Similar to the strstr function, but case independent
  • strlen - Returns the length of a string
  • strnatcasecmp - Compare case-insensitive strings using an algorithm
  • strnatcmp - Comparing strings using the "natural ordering" algorithm
  • strncasecmp
  • strncmp - Case-insensitive, binary-safe comparison of the first n characters of strings
  • strpos - Finds the first occurrence of a substring in a string
  • strrchr
  • strrev - Reverses a string
  • strripos - Returns the position of the last occurrence of a substring, case insensitive
  • strrpos - Finds the last occurrence of a character in a string
  • strspn - Returns the length of the portion at the beginning of the string corresponding to the mask
  • strstr - Finds the first occurrence of a substring
  • strtok - Splits a string
  • strtolower - Converts a string to lowercase
  • strtoupper - Converts a string to uppercase
  • strtr - Converts given characters
  • str_ireplace - A case-insensitive variant of the str_replace() function.
  • str_pad - Pads a string with another string to a given length
  • str_repeat - Returns a repeating string
  • str_replace - Replaces the search string with the replacement string
  • str_rot13 - Performs a ROT13 transformation on a string
  • str_shuffle - Shuffles characters in a string
  • str_split - Converts a string to an array
  • str_word_count - Returns information about the words in a string
  • substr - Function returns part of a string
  • substr_count - Counts the number of occurrences of a substring in a string
  • substr_replace - Replaces part of a string
  • trim - Removes spaces from the beginning and end of a string
  • ucfirst - Converts the first character of a string to uppercase
  • ucwords - Converts the first character of each word in a string to uppercase
  • vprintf - Prints a formatted string
  • vsprintf - Returns a formatted string
  • wordwrap - Wraps a line for a given number of characters using a line break character
  • Features of comparison operators as applied to strings.

    $one = 1; // Number one. $zero = 0; // Assign the number zero. if ($one == "") echo 1; // Obviously not equal - does not output 1. if ($zero == "") echo 2; //* Attention! Contrary to expectations, it prints 2! if ("" == $zero) echo 3; //* And this won't help either - it prints!.. if ("$zero" == "") echo 4; // That's right. if (strval($zero) == "") echo 5; // This is also correct - it does not print 5. if ($zero === "") echo 6; // Better way, but doesn't work in PHP 3.

    chop()

    The chop() function returns a string after removing trailing spaces and newlines. The chop() function syntax is:

    string chop(string string)

    In the following example, the chop() function removes extra newlines:

    $header = "Table of Contents\n\n"; $header = chop($header); // $header = "Table of Contents"

    str_pad()

    The str_pad() function pads a string to a certain length with the given characters and returns the formatted string. Syntax of the str_pad() function:

    string str_pad (string string, int pad_length [, string pad [, int pad_type]])

    If the optional padding parameter is not specified, the string is padded with spaces. Otherwise, the string is padded with the given characters. By default, the line is padded on the right; however, you can pass the padding_type parameter STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH, which will pad the row in the specified direction. The example demonstrates string padding with the str_pad() function with default parameters:

    $food = "salad"; print str_pad ($food, 5): // Prints the string "salad" The following example uses the optional parameters of the str_pad() function: $header = "Table of Contents"; print str_pad ($header, 5, "=+=+=" , STR_PAD_BOTH); // The browser displays the line =+=+= Tabe of Contents=+=+="

    trim()

    The trim() function removes all whitespace from both ends of a string and returns the resulting string. The trim() function syntax is:

    string trim (string country]

    The spaces that are removed include the special characters \n, \r, \t, \v, and \0.

    ltrim()

    The lrim() function removes all whitespace and special characters from the left edge of a string and returns the resulting string. ltrim() function syntax:

    string ltrim (string string)

    The function removes the same special characters as the trim() function.

    strlen()

    Determining String Length

    The length of a string in characters can be determined using the strlen() function. Syntax of the strlen() function:

    int strlen (string string)

    The following example demonstrates how to determine the length of a string using the strlen() function:

    $string = "hello"; $length = strlen($string); // $length = 5

    Comparing two strings

    Comparing two strings is one of the most important string operations in any language. Although this problem can be solved in several different ways, there are four string comparison functions in PHP:

    strcmp()

    The strcmp() function compares two strings in a case-sensitive manner. Syntax of the strcmp() function: int strcmp (string string1, string string2)

    Once the comparison is complete, strcmp() returns one of three possible values:

    • 0 if line1 and line2 are the same;
    • < 0, если строка1 меньше, чем строка2;
    • > 0 if string2 is smaller than string1.

    $sthng1 = "butter"; $string2 = "butter"; if ((strcmp($string1. $string2)) == 0) : print "Strings are equivalent!"; endif; // The if command returns TRUE

    strcasecmp()

    The strcasecmp() function works exactly the same as strcmp(), with one exception - the comparison does not take into account the case of characters. The syntax of the strcasecmp() function is:

    int strcasecmp (string string1, string string2)

    The following snippet compares two identical strings:

    $string1 = "butter"; $string2 = "Butter"; if ((strcmp($string1, $string2)) == 0) : print "Strings are equivalent!"; endif; // The if command returns TRUE

    strspn()

    The strspn() function returns the length of the first segment of string1 containing the characters present in string2. The strspn() function syntax is:

    int strspn (string string1, string string2)

    The following snippet shows how the strspn() function is used to verify a password:

    $password = "12345"; if (strspn($password, "1234567890") != strlen($password)) : print "Password cannot consist solely of numbers!"; endif:

    strcspn()

    The strcspn() function returns the length of the first segment of string1 that contains characters not present in string2. Syntax of the strcspn() function:

    int strcspn (string string1, string string2)

    The following snippet uses the strcspn() function to check the password:

    $password = "12345"; if (strcspn($password, "1234567890") == 0) : print "Password cannot consist solely of numbers!"; endif;

    Processing string data without using regular expressions

    When processing large amounts of information, functions regular expressions greatly slow down program execution. These functions should only be used when processing relatively complex strings where regular expressions are truly necessary. If text analysis is performed relatively simple rules, you can use standard PHP functions, which significantly speed up processing. All these functions are described below.

    strtok()

    The strtok() function splits a string into tokens using the separators specified by the second parameter. The strtok() function syntax is:

    string strtok (string string, string delimiters)

    The strtok() function has one strange thing: in order to completely split a string, the function must be called several times in succession. The next time the function is called, it extracts the next token from the string. In this case, the string parameter is specified only once - the function tracks the current position in the string until the string is completely parsed into tokens or is specified new parameter line. The following example demonstrates splitting a string using multiple delimiters:

    $info = "WJ Gi1more: [email protected]| Columbus, Ohio"; // Delimiters - colon (:), vertical bar (|) and comma (.) $tokens = ":|,"; $tokenized = strtok($info, $tokens); // Print array elements $tokenized while ($tokenized) : echo "Element = $tokenized
    "; // Please note that subsequent calls to strtok // do not pass the first argument $tokenized = strtok($tokens); endwhile; Result: Element = WJGilmore Element = [email protected] Element = Columbus Element = Ohio

    parse_str()

    The parse_str() function parses pairs in a string and assigns values ​​to variables in the current scope. Syntax of the parse_str() function:

    void parse_str (string string)

    The parse_str() function is especially useful when parsing URLs containing HTML form data or other rich information. The following example parses information passed through a URL. The line represents standard way transfer of data between pages, either compiled into a hyperlink or entered into HTML form:

    $url = "fname=wj&lname=gilmore&zip=43210"; parse_str($url); // After parse_str() is executed, the following variables are available: // $fname = "wj": // $lname = "gilmore"; // $zip = "43210"

    Because this function was designed to work with URLs, it ignores the ampersand (&) character.

    explode()

    The explode() function splits a string into elements and returns those elements as an array. Explode() function syntax:

    array explode (string delimiter, string string [, int threshold])

    Splitting occurs on each instance of the separator, and the number of resulting fragments can be limited by the optional threshold parameter.

    The explode() function demonstrates splitting a string in the following example:

    $info = "wilson | baseball | Indians"; $user = explode("|", $info); // $user = "wilson"; // $user = "baseball"; // $user = "Indians";

    The explode() function is almost identical to the POSIX regular expression function split() described above. The main difference is that passing regular expressions as parameters is only allowed when calling split().

    implode()

    If the explode() function splits a string into array elements, its counterpart, the implode() function, merges the array into a string. Implode() function syntax:

    string implode (string separator, array fragments)

    Forming a string from an array is demonstrated in the following example:

    $ohio_cities = array("Columbus", "Youngstown", "Cleveland", "Cincinnati"); $city_string = implode("l", $ohio_cities); // $city_string = "Columbus | Youngstown | Cleveland | Cincinnati";

    implode() has an alias, the join() function.

    strpos()

    The strpos() function finds the first instance of a given substring in a string. The strpos() function syntax is:

    int strpos (string string, string substring [, int offset])

    The optional offset parameter specifies the position at which the search should begin. If the substring is not found, strpos() returns FALSE (0).

    The following example determines the position of the first occurrence of a date in the log file:

    $log = "206.169.23.11:/www/:2000-08-10 206.169.23.11:/www/logs/:2000-02-04 206.169.23.11:/www/img/:1999-01-31"; // In what position in the journal does the year 1999 first appear? $pos = strpos($log, "1999"); // $pos = 95. because the first instance of "1999" // is at position 95 of the line contained in the $log variable

    strpos()

    The strrpos() function finds the last instance of a given character in a string. The strrpos() function syntax is:

    int strpos (string string, char character)

    In terms of capabilities, this function is inferior to its counterpart - the strpos() function, since it allows you to search only for a single character, and not for the entire string. If a string is passed as the second parameter to strrpos(), only its first character will be used in the search.

    str_replace()

    The str_replace() function searches a string for all occurrences of a given substring and replaces them with a new substring. Syntax of the str_replace() function:

    string str_replace (string substring, string replacement, string string)

    The substr_replace() function, described later in this section, allows you to replace only a specific part of a string. The following shows how the str_replace() function is used to perform a global replacement on a string.

    If the substring never appears in the string, the original string is left unchanged:

    $favorite_food = "My favorite foods are ice cream and chicken wings"; $favorite_food = str_replace("chicken_wings", "pizza", $favohte_food); // $favorite_food = "My favorite foods are ice cream and pizza"

    strstr()

    The strstr() function returns the portion of a string beginning with the first occurrence of a given substring. Syntax of the strstr() function:

    string strstr (string string, string substring)

    The following example uses the strstr() function to extract a domain name from a URL:

    $url = "http://www.apress.com"; $domain - strstr($url, "."); // $domain = ".apress.com"

    substr()

    The substr() function returns the portion of a string starting at a given starting position and having a given length. Substr() function syntax:

    string substr (string string, int start [, int length])

    If the optional length parameter is not specified, the substring is assumed to begin at the specified starting position and continue to the end of the string. There are four things to consider when using this feature:

    • if the start parameter is positive, the returned substring begins at the position of the line with the given number;
    • if the start parameter is negative, the returned substring begins at position (string length - start);
    • if length is positive, the returned substring includes all characters from start to start+length. If the last value exceeds the length of the string, characters up to the end of the string are returned;
    • if length is negative, the returned substring ends at the specified distance from the end of the string.

    Remember that the start parameter specifies the offset from the first character of the line; so the returned string actually starts at character number (start + 1).

    The following example demonstrates substr() substring substring:

    $car = "1944 Ford"; Smodel = substr($car, 6); // Smodel = "Ford"

    Example with a positive length parameter:

    $car = "1944 Ford"; $model = substr($car, 0, 4); // $model = "1944" Example with a negative length parameter: $car = "1944 Ford"; $model = substr($car, 2, -5); // $model = "44"

    substr_count()

    The substr_count() function returns the number of occurrences of a substring in a given string. The syntax of the substr_count() function is: int substr_count (string string, string substring) In the following example, the substr_count() function counts the number of occurrences of the substring ain: $tng_twist = "The rain falls mainly on the plains of Spain"; $count = substr_count($tng_twist, "ain"); // $count = 4

    substr_replace()

    The substr_replace() function replaces the part of a string that starts at a given position. If the optional length parameter is specified, a fragment of the specified length is replaced; otherwise, the replacement is performed along the entire length of the replacement string. The syntax of the substr_replace() function is:

    string substr_replace (string string, string replacement, int start [, int length])

    The start and length parameters are set according to certain rules:

    • if the start parameter is positive, the replacement starts from the specified position;
    • if the start parameter is negative, the replacement starts at position (string length -start);
    • if the length parameter is positive, a fragment of the specified length is replaced;
    • if length is negative, the replacement ends at position (string length -length).

    Simple text replacement using substr_replace() is demonstrated in the following example:

    $favs = " "s favorite links"; $name = "Alessia"; // Parameters "0, 0" mean that the fragment to be replaced begins // and ends at the first position of the line. $favs - substr_replace($favs, $name , 0, 0); print $favs:

    Result:

    Alessia's favorite links

    Converting strings and files to HTML format and vice versa

    Converting a string or an entire file to a format suitable for viewing in a web browser (or vice versa) is easier than it might seem at first glance. PHP has special functions for this.

    Converting text to HTML

    Quick conversion plain text to the web browser format is a very common task. The functions described in this section will help you solve it.

    nl2br()

    The nl2br() function replaces all newline characters (\n) with equivalent HTML constructs.

    nl2br() function syntax:

    string nl2br (string string)

    Newline characters can be either visible (that is, explicitly included in the line) or invisible (for example, entered in the editor). The following example converts a text string to HTML format by replacing the \n characters with line breaks:

    // Text string, displayed in the editor. $text_recipe = "Party Sauce recipe: 1 can stewed tomatoes 3 tablespoons fresh lemon juice Stir together, server cold."; // Convert newlines to
    $htinl_recipe = nl2br($text_recipe) Subsequent output of $html_recipe will return the following HTML text to the browser: Party Sauce recipe:
    1 can stewed tomatoes
    3 tablespoons fresh lemon juice
    Stir together, server cold.

    htmlentities()

    The htmlentities() function converts characters into equivalent HTML constructs. The syntax for the htmlentities function is:

    string htmlentities (string string)

    The following example performs the necessary substitution of string characters for output to the browser:

    $user_input = "The cookbook, entitled Cafe Francaise" costs

    The htmlentities() function currently only works for ISO-8559-1 (ISO-Latin-1) encoding characters. Also, it doesn't convert spaces to as you would expect.

    htmlspecialchars()

    The htmlspecialchars() function replaces certain characters that have special meaning in the context of HTML with equivalent HTML constructs. The syntax of the htmlspecialchars() function is:

    string htmlspecialchars (string string)

    The html special chars() function currently converts the following characters: & converts to &; " " is converted to "; is converted to >.

    Specifically, this feature helps prevent users from typing HTML markup in interactive web applications (such as online forums). Mistakes in HTML markup can cause the entire page to not form correctly. However, there is more to this problem effective solution- completely remove tags from a string using the strip_tags() function.

    The following example demonstrates the removal of potentially dangerous characters by the htmlspeclalchars() function:

    $user_input = "I just can"t get of PHP & those fabulous cooking recipes!"; $conv_input = htmlspecialchars($user_input); // $conv_input = "I just can"t<> of PHP & those fabulous cooking recipes!"

    If the htmlspecialchars() function is used in combination with nl2br(), then the latter should be called after htmlspecialchars(). Otherwise the designs
    , generated by calling nl2br() are converted to visible characters.

    get_html_translation_table()

    The get_html_translation_table() function provides a convenient means of converting text to HTML equivalents. The syntax of the get_htrril_translation_table() function is:

    string get_html_translation_table (int table)

    The get_html_translation_table() function returns one of two translation tables (defined by the table parameter) used in the operation of the standard functions htmlspecialchars() and htmlentities(). The return value can be used in combination with other standard function, strtr(), to convert text to HTML code.

    The table parameter takes one of two values:

    • HTML_ENTITIES;
    • HTML_SPECIALCHARS.

    The following example uses the get_html_translation_table() function to convert text to HTML:

    $string = "La pasta e il piatto piu amato in Italia"; $translate = get_html_translation_table(HTML_ENTITIES); print strtr($string, $translate); // Special symbols are converted to HTML constructs // and display correctly in the browser.

    By the way, the array_flip() function allows you to convert text to HTML in the opposite direction and restore the original text. Suppose that instead of printing the result of strtr() in the previous example, we assigned it to the $translated string variable.

    In the following example, the original text is restored by the array_flip() function:

    $translate = array_flip($translate); $translated_string - "La pasta é il piatto piú amato in Italia"; $original_string = strtr($translated_string, $translate); // $original_string = "La pasta e il piatto piu amato in Italia";

    strtr()

    The strtr() function translates a string, that is, it replaces all the characters in the source string with the corresponding characters in the destination string. The strtr() function syntax is:

    string strtr (string string, string source, string destination)

    If the source and destination strings are of different lengths, the long string is truncated to fit the short string.

    There is an alternative syntax for calling strtr() with two parameters; in this case, the second parameter contains an associative array whose keys correspond to the substrings being replaced, and whose values ​​correspond to the replacing substrings. The following example replaces HTML tags with XML-like constructs:

    " => "

    ", "" => "

    "); $string = "

    Today In PHP-Powered News

    "; print strtr($string, $source); // Prints the string " Today in PHP-Powered News" ?>

    Convert HTML to Plain Text

    Sometimes you need to convert an HTML file into plain text. The functions described below will help you with this task.

    strip_tags()

    The strip_tags() function strips all HTML and PHP tags from a string, leaving only text in it. The strip_tags() function syntax is:

    string strip_tags (string string [, string allowed_terri])

    The optional allowed_tags parameter allows you to specify tags that should be skipped during the deletion process.

    Below is an example of removing all HTML tags from a string using strip_tags():

    $user_input = "I just love PHP and gourment recipes!"; $stripped_input = strip_tags($user_input); // $stripped_input = "I just love PHP and gourmet recipes!";

    The following example removes not all, but only some tags:

    $input = "I love to eat!!"; $strip_input = strip_tags ($user_input, " "); // $strip_input = "I love to eat!!";

    Removing tags from text is also done by the fgetss() function.

    get_meta_tags()

    Although the get_meta_tags() function is not directly related to text transformation, it is quite useful feature, which should be mentioned. Get_meta_tags() function syntax:

    array get_meta_tags (string file_name/URL [, int include_path])

    The get_meta_tags() function is designed to search a file HTML tags META.

    META tags contain information about a page, used primarily by search engines. These tags are inside a pair of tags... . The use of META tags is demonstrated in the following snippet (let's call it example.html because it will be used in Listing 8.2): PHP Recipes The get_meta_tags() function searches the document head for tags that begin with the word META and stores the tag names and their contents in an associative array. Listing 8.2 demonstrates this function applied to the example.html file. Listing 8.2. Extracting META tags from HTML file function get_meta_tags()

    $meta_tags = get_meta_tags("example.html"): // The $meta_tags variable contains an array with the following information: // $meta_tags["keywords"] = "PHP, code, recipes, web" // $meta_tags["description" ] = "PHP Information" // $meta_tags["author"] = "KDG";

    An interesting detail: META tag data can be extracted not only from files located on the server, but also from other URLs.

    Convert a string to upper and lower case

    There are four functions in PHP designed to change the case of a string:

    strtolower()

    The strtolower() function converts all alphabetic characters in a string to lowercase. The strtolower() function syntax is:

    string strtolower(string string)

    Non-alphabetic characters are not changed by the function. Converting a string to lowercase using the strtolower() function is demonstrated in the following example:

    $sentence = "COOKING and PROGRAMMING PHP are my TWO favorite!"; $sentence = strtolower($sentence); // After the function call, $sentence contains the string // "cooking and programming php are my two favorite!"

    strtoupper()

    Strings can be converted not only to lower case, but also to upper case. The conversion is performed by the strtoupper() function, which has the following syntax:

    string strtoupper (string string)

    Non-alphabetic characters are not changed by the function. Converting a string to uppercase using the strtoupper() function is demonstrated in the following example:

    $sentence = "cooking and programming PHP are my two favorite!"; $sentence = strtoupper($sentence); // After the function call, $sentence contains the string // "COOKING AND PROGRAMMING PHP ARE MY TWO FAVORITE!"

    ucfirst()

    The ucfirst() function converts the first character of a string to uppercase, provided it is an alphabetic character. ucfirst() function syntax:

    string ucfirst (string string)

    Non-alphabetic characters are not changed by the function. The conversion of the first character of a string by the ucfirst() function is demonstrated in the following example:

    &sentence = "cooking and programming PHP are my two favorite!"; $sentence = ucfirst($sentence); // After the function call, $sentence contains the string // "Cooking and programming PHP are my two favorite!"

    ucwords()

    The ucwords() function converts the first letter of each word in a string to uppercase. Syntax of the ucwords() function:

    string ucwords (string string")

    Non-alphabetic characters are not changed by the function. A "word" is defined as a sequence of characters separated from other elements of the string by spaces. The following example demonstrates how the ucwords() function converts the first characters of words:

    $sentence = "cooking and programming PHP are my two favorite!"; $sentence = ucwords($sentence); // After the function call, $sentence contains the string // "Cooking And Programming PHP Are My Two Favorite!"

    strhr()

    strrchr("string", "o") - Finds the last occurrence of a substring

    If the substring is not found, returns FALSE.

    Unlike strchr(), if the search string consists of more than one character, only the first character is used.

    If the second parameter is not a string, it is cast to an integer and treated as a character code.

    // get the last directory from $PATH $dir = substr(strrchr($PATH, ":"), 1); // get everything after the last line break $text = "Line 1\nLine 2\nLine 3"; $last = substr(strrchr($text, 10), 1);

    highlight_string()

    highlight_string - highlight string syntax.

    mixed highlight_string (string str [, bool return])

    The highlight_string() function outputs a syntax-colored version of str using the colors defined in PHP's built-in syntax highlighting.

    If the second return parameter is TRUE, then highlight_string() will return the highlighted code version as a string instead of printing it. If the second parameter is not TRUE, highlight_string() will return TRUE on success, FALSE on failure.

    Note: 1.the return parameter became available starting from PHP 4.2.0. Before this it worked as by default, i.e. FALSE.
    2.The Highlight_String() function distinguishes PHP code by tags. show_source()- synonym highlight_file(). To change the default highlight color, use the following PHP directives:

    Highlight.bg #FFFFFF highlight.comment #FF8000 highlight.default #0000BB highlight.html #000000 highlight.keyword #007700 highlight.string #DD0000 in .htaccess: php_flag highlight.bg #FFFFFF in PHP: if(@ini_get("highlight .bg")=="") ...

    addslashes()

    - Escapes special characters in a string

    Returns a string with a backslash (\) added before each special character, for example for later use of this string in a database query.

    The single quote ("), double quote ("), backslash (\) and NUL (NULL byte) are escaped.

    $str = "Is your name O"reilly?"; // outputs: Is your name O\"reilly? echo addslashes($str);

    stripslashes

    - Removes escaping characters produced by the addslashes() function Removes escaping backslashes. (\" is converted to ", etc.). Double backslashes (\\) are converted to single backslashes (\).

    wordwrap()

    Wraps a line for a given number of characters using a line break // Using wordwrap(). function cite($ourText, $maxlen=60, $prefix="> ") ( $st = wordwrap($ourText, $maxlen-strlen($prefix), "\n"); $st = $prefix.str_replace( "\n", "\n$prefix", $st); return $st; echo cite("The first Matrix I designed was quite naturally perfect, it was a work of art - flawless, sublime. A triumph equaled only by its monumental failure. The inevitability of its doom is apparent to me now as a consequence of the imperfection inherent in every human being. Thus, I redesigned it based on your history to more accurately reflect the varying grotesqueries of your nature. was again frustrated by failure.", 20);

    > The first Matrix I > designed was quite > naturally > perfect, it was a > work of art - > flawless, sublime. > A triumph > equaled only by > its monumental > failure. The > inevitability > of its doom is > apparent to me now > as a consequence > of the > imperfection > inherent in every > human being. , > I > redesigned it > based on your > history to more > accurately reflect > the varying > grotesqueries of > your nature. > However, I was > again > frustrated by > failure.


    Read more:

    Websites can be divided into static and dynamic. After mastering HTML and CSS, which allow you to make a beautiful business card on the Internet, many people think about how to create a dynamic website in PHP. At the same time, the layout designer must take into account that he is now starting to study web programming: the principles of working with the site will be different. One of the first problems that a beginner in PHP faces is working with strings, reading and processing them.

    It's worth noting that PHP means a large number of methods, so you should start studying them with the simplest manipulations, such as outputting a string, searching, getting or replacing a substring, changing case and returning the length of a string. Many functions do not work well with Cyrillic characters. Therefore, all examples are written in English for clarity. For Cyrillic strings, the same functions are used, but with the mb_ prefix (for example, mb_strpos()). Before using analogs, you need to uncomment the line in php.ini; extension=php_mbstring.dll, simply removing the semicolon.

    Creating and Outputting a String

    We will analyze the output of a string to the screen using the well-known echo language construct. The programmer can output the line immediately:

    echo "This is a New Line"

    or first create a variable and then print it to the screen:

    $str = "This is a New Line";

    If you need to display several lines in one, then resort to concatenation:

    echo "This" . "New". " Line";

    $str1 = "This";

    $str2 = "New";

    $str3 = "String";

    echo $str1 . $str2 . $str3;

    In the latter case, the screen will display This is NewLine. A space can be added immediately when calling echo:

    echo $str1 . " " . $str2 . " " . $str3;

    In this case, the screen will display: “This is a New Line.” Concatenation is possible not only during output, but also when creating a string:

    $str1 = "This";

    $str2 = "New";

    $str3 = "String";

    $string = $str1 . " " . $str2 . " " . $str3;

    echo $string;

    Echo displays both Cyrillic and Cyrillic. If one of the variables contained a number, then during concatenation this number will be converted into the corresponding string:

    $sum = $i + $i; //now $sum contains the number 4

    echo $i . " + " . $i . " = " . $sum;

    The screen will display: "2 + 2 = 4".

    Service symbols

    Let's say a string is defined with ($string = "Like this"). Then you can absolutely safely use control sequences:

    • \n performs a line feed;
    • \r returns carriage;
    • \" escapes double quotes:
      • echo "String with \"double\" quotes"; //String with double quotes
    • \$ escapes dollar;
    • \\ escapes a backslash.

    There are many more sequences, all of them can be found in the official PHP documentation.

    How to find the position of the first occurrence of a substring

    Let's say we have a simple line:

    We also have two lines with names:

    $name = "Yemelyan";

    $anotherName = "Katherine";

    We need to know if the first line contains these two names. To do this, use the strpos($str, $search) function. It returns the position of the searched substring, $search, if that string is contained in the original, $str. Otherwise, the function returns the boolean value false. For example, strpos($string, $anotherName) will return false, while strpos($string, $name) will return an integer. The code will be like this (we will write the version when the position is displayed on the screen):

    $string = "My name is Yemelyan and I am 27 year old";

    $name = "Yemelyan";

    $anotherName = "Katherine";

    echo strpos($string, $anotherName); //will display false

    echo strpos($string, $name); //will print the position of the first occurrence of the substring

    Please note that line numbering starts from zero, that is, in our case last line will output the number 11 (spaces also count).

    Finding the position of the last occurrence of a substring and pitfalls

    If the strpos() function returns the position of the first occurrence, then its inverse function strrpos() searches for the last occurrence of the substring.

    There are some pitfalls associated with starting numbering. This is worth considering: in PHP, working with strings can be complicated by restrictions in comparisons. So, it is better not to use the comparison operator with negation: strpos($str, $search)!=false. In any version of PHP, examples with such an equivalence may not work correctly, because line numbering starts from zero, and in the logical interpretation, 0 is false. This also applies to the strrpos() function.

    How to find the number of occurrences of a substring

    Often you need to find not the position of the first or last occurrence of a substring in a string, but the total number of them. To do this, use the substr_count() function, which processes at least two variables: substr_count($str, $search). Returns an integer. If it is necessary to reduce the search area by string, then two more variables are passed to the function: the beginning and end of the string, respectively. That is, the function in this case is called like this: substr_count($str, $search, $start, $end). The function will search for the substring $search in the interval from $start to $end of the original string $str. If the string is not found, the function will return zero.

    How to change the case of a string in PHP: examples

    Changing case is often used to compare strings and Let's say the user must enter the name of the supreme god in the program. There is an option "One", with which the user's answer will be compared. If the entered text does not match the existing one (for example, the user writes “one” or “ONE”), the program will return false instead of true. To avoid this, the case change function is used. This is often used if a PHP site has tags: instead of hundreds of variations of the word "personal" ("Personal", "personal", "PERSONAL", etc.) there is only one lowercase tag.

    The strtolower() function changes case to lower case. Let's say there is a line $catName = "Fluffy". The function strtolower($catName) will return the string "fluffy". You can change the case to uppercase using the strtoupper() function.

    How to find the length of a string in PHP: working with functions

    Often you need to find the length of a string. For example, in PHP, working with strings of this kind may be necessary when creating a loop. To search for a string, use the strlen() function, which returns a number - the number of characters. We must not forget that the last character will have the number strlen($str)-1, since the numbering starts from zero.

    Getting and replacing a substring in PHP: working with strings

    Getting a substring is done by the substr() function, which can take two or three arguments: substr($str, $start, $end). Let's say we have $string = "Fluffy cat" and we want to get the substring from the second to the fourth character. Since numbering starts from zero, the variable with this substring will look like this: $newString = substr($string, 1, 4). If we enter $newString = substr($string, 1), we will get a substring from the second character to the last (that is, "luffy"). This code is identical full code strings using strlen(): substr($string, 1, strlen($string)).

    To replace a substring, use the str_replace() function, which takes three variables: str_replace($subStr, $newSub, $str). Unlike many functions, str_replace() works correctly with Cyrillic characters and has no analogue with a prefix. Example:

    $str = "The weather is terrible today!";

    $newStr = str_replace("terrible", "wonderful", $str); //Wonderful weather today!

    Converting a string to a number

    Everyone who learns web programming sooner or later has to convert a string to a number. To do this, two similar functions are used: intval() and floatval(), each of which takes one $string variable. They differ from each other only in the type of data returned: intval() returns an integer, and floatval() returns a floating point number.

    To use both intval() and floatval(), the string must begin with digits, and these will be converted to a number. If any set of letters comes after the numbers, they will simply be ignored. If the string starts with letters, using the function will return zero. Ideally, the line should contain only numbers.

    Converting a number to a string

    Often you need to convert numbers into a string. Say, if you need to take half a number and square it (for example, check whether the equality is true: 88 x 88 + 33 x 33 = 8833). In this case, the strval() function is used, which returns a string with a number. After that with new line you can perform all other actions: change, search for the occurrence of a substring and other functions. If necessary, the string can be converted back into a number using the method already described above.

    The article examined only a small part of all functions related to strings. Some undescribed functions work with symbols, but most were not included in the material due to specificity. To become familiar with these features, you should proceed to reading the official PHP documentation, which displays the latest information.

    Date of publication: 01/03/2018

    Greetings, friends! 🙂

    I think that, if not all, then certainly most of you have encountered in practice the need to read information from txt files at the server script level. At least, I had several such cases, the last of which I will tell you about today.

    There is nothing complicated about this, but sometimes your eyes run wide from the abundance of options provided by server-side languages. If we talk specifically about PHP, which I am currently programming in, then using its functions you can read the contents of files line by line, or entirely into a string, or into an array, and for the latter option there are several more ways... These are the pies :)

    Unfortunately, these methods work at different speeds for files of different structures, and there is not a single word about their speed in the official documentation; this can only be judged in practice, going through all possible options.

    So today I will show you my work various functions PHP for reading files, so that when you need to create a PHP file parser for real-world problems, you know what to choose from. I’ll also tell you exactly how to make the right choice in “combat conditions.”

    Go! 🙂

    Creating a PHP file parser - initial conditions

    Before we begin, a few words about the task for which I created a file parser in PHP, and then chose the optimal one from the implemented options.

    I once had a problem at work where the database stored user phone numbers in the wrong format. Naturally, I fixed the bug itself without any problems.

    But what to do with incorrect information that was already stored in the database at that time? Naturally, it had to be replaced with the correct one.

    For this I was given text file with user IDs and their phone numbers that needed to be transferred to the database.

    I must say, it turned out to be quite weighty: 352 KB and 8223 lines of text, each of which contained the user ID and his phone number in the format user_id:phone_number.

    In a word, the whole task was to read line by line PHP file means of extracting the identifier and phone number from the string and then updating the user’s phone number in the database, found by ID.

    My project was implemented on the Yii PHP framework, therefore in further code examples you will find elements of its API for working with the database, in particular, so don’t be alarmed :)

    After analyzing the constructions available in the language, as well as the experience of other developers, collected bit by bit on the Internet, I was able to identify 4 methods, which I will further demonstrate to you.

    Well, then I’ll tell you by what criteria and how exactly I chose the best option among them. And, of course, I will share the results :)

    So this article is an excellent training in patience :) The essence of it will be a detailed study of the following material up to the results that will await you at the end. Along the way, by the way, you can also work on your imagination, imagining exactly how the ideal option will be chosen.

    Reading a file in PHP line by line using fgets()

    As a result, a PHP file parser that implements this algorithm, accepted from me next view:

    find("unique_id IN (:id1, :id2)", array(":id1" => strtolower($params), ":id2" => strtoupper($params))); if ($client) ( $client->phone = str_replace(array("\r", "\n"), "", $params); $client->save(); ) ) ) if (!feof ($fh)) ( echo "Error: unexpected fgets() fail\n"; ) fclose($fh); ) else echo "Check the filename, file doesn't exist!"; )

    I’ll decipher my writing a little if anyone has difficulty understanding it.

    At the very beginning, the variable $filename the value is assigned to the name of the file that will be parsed, with the full path to it. Next comes PHP checking whether the file exists and whether it is readable using functions file_exists() And is_readable() respectively.

    If everything is OK, then open the file using the function fopen(), which is called with the PHP error control statement to turn off the output of errors generated by this function. I decided to use it to generate my own error message instead of the standard one.

    If we succeed in opening the file, then we go through all its lines in a loop until the file ends, and, if the line is not empty, we separate it at the colon character with the function explode().

    Then we check that the user id and his phone number are not empty, look for the user in the database by ID and, if one exists, then update his phone number by first removing the hyphen and new line characters from the number value.

    Well, I also used PHP functions strtolower() And strtoupper() to check the existence in the database of a user with identifiers that could be registered in different registers, because in my case they consisted of symbols and numbers.

    PHP parsing a file into an array using file()

    This method of reading a file in PHP involves using the function file(), which opens a file and puts its contents into an array. In this case, the elements of the array will be exactly the lines of the file being read, which is perfect in my situation.

    The code for this version of the PHP file parser is as follows:

    find("unique_id IN (:id, :id2)", array(":id" => strtolower($params), ":id2" => strtoupper($params))); if ($client) ( $client->phone = str_replace(array("\r", "\n"), "", $params); $client->

    As you can see, this differs from the previous method of reading a file in PHP only in its beginning, where the file is opened and immediately read by the function file() instead of a bunch fopen() + fgets(), as before.

    PHP reading a file into a variable using fread()

    Another PHP function for parsing a file is fread(), with which you can read different fragments of a file of a specified length. To read the entire file in PHP, I specified the file size obtained using the function as the fragment size filesize():

    find("unique_id IN (:id1, :id2)", array(":id1" => strtolower($params), ":id2" => strtoupper($params))); if ($client) ( $client->phone = str_replace(array("\r", "\n"), "", $params); $client->save(); ) ) ) ) else echo " Check the filename, file doesn"t exists!";

    This method of reading a file using PHP means is, in fact, very similar to the previous one, because, despite the fact that with the help of PHP, data from the file is initially read not into an array, but into a string variable, then it is still converted into an array , because It's easier to work with than a string.

    The easiest way to convert a string into an array in PHP is to use the explode() function, which was already used today, and passed the beginning of the string as a delimiter.

    Creating a PHP file parser based on file_get_contents()

    Well, and finally, I decided to implement PHP file parsing using the function file_get_contents(), which is precisely intended for reading the entire file into a line, i.e. works practically like fread($fp, filesize($filename)).

    The only exception is that file_get_contents() itself opens the file and reads it, while to use fread() you had to first open the file through fopen() and get its pointer for further use.

    In general, the PHP file parser code based on file_get_contents() will be almost the same as in the previous case:

    find("unique_id IN (:id1, :id2)", array(":id1" => strtolower($params), ":id2" => strtoupper($params))); if ($client) ( $client->phone = str_replace(array("\r", "\n"), "", $params); $client->save(); ) ) ) ) else echo " Check the filename, file doesn"t exists!";

    That's all. It's time to sum up the performance of all the listed options and find out which PHP file parser turned out to be the most optimal for further use.

    What is the best way to process files in PHP?

    To choose the most optimal one from the found options, i.e. the fastest, I decided to determine in each case. To do this, I used the technique described in the article at the link.

    The PHP file reading functions themselves are quite fast, so in order to achieve at least some more or less tangible figures for their operating time, I deliberately left database operations in the tested fragments, which were the same in all cases.

    For convenience, I also decided to round the running time of the PHP script to the third decimal place, i.e. up to thousandths of seconds (although it could have been limited to hundredths, in fact).

    I remember when I was at school and writing my scientific work in physics (yes, I had such an experience :) during its defense in front of university teachers, I was constantly reproached for not having enough experiments (I did 3 experiments for each case). The “luminaries of science” named figures of 100, or at least 10 experiments to compare different situations, so that some kind of comparison could be made and minimize the likelihood of one being accidentally superior to the other.

    Yes, I got a hard time from them back then, but I learned their recommendations so well that I remember about it even now, although more than 10 years have passed since then. Moreover, these recommendations were indeed based on the laws of mathematical statistics and probability theory.

    Well, in this article I do not pretend that my current experiments are scientific, so I considered the number of 100 experiments to be too large, and the process of conducting them to be too tedious.

    As a result, I decided to limit myself to 10 experiments for each version of the PHP file parser, which, as it turned out in the end, was quite enough to identify a clear leader without any manipulation of facts and clues in hundredths and thousandths of a second of superiority.

    The results of calculations of the operating time of the PHP file parsers I developed are presented in the following table and sorted by the PHP functions on which they work.

    Experiment fgets() file() fread() file_get_contents()
    1 9,147 9,722 10,539 2,008
    2 8,950 9,006 9,495 1,733
    3 8,821 8,845 9,207 1,642
    4 8,717 8,876 8,931 1,758
    5 9,010 9,091 8,703 1,635
    6 9,110 8,640 9,712 1,633
    7 9,074 9,626 9,13 1,645
    8 8,886 9,204 9,048 1,701
    9 8,667 8,918 9,438 1,713
    10 8,852 9,197 9,537 1,567
    Average 8,923 9,113 9,374 1,704

    As you can see, in addition to the script execution times in each of the 10 experiments, I decided to calculate the average temperature in the hospital :)

    Namely, the arithmetic average operating time of each PHP file parser so that the leader can be identified.

    And it turned out to be, as you can see, the last option, implemented based on the function file_get_contents(), which reads the contents of the file into a string variable and then converts it into an array and processes it in a loop.

    All other versions of PHP file parsers work at approximately the same speed.

    Why exactly he overtook his competitors, I honestly don’t have the slightest idea. I can only assume that the operation of reading a file into a string using file_get_contents() requires fewer resources than generating a ready-made array of strings using file().

    And the superiority over fgets() and fread() can be attributed to the fact that before using them you need to open the file using fopen(), which takes time.

    Yes, in fact, it doesn’t matter, because... the numbers speak for themselves: thanks to the use of the function file_get_contents() The PHP file parser based on it works 5 times faster than others, which influenced my decision to use it in practice.

    Parsing a file in PHP - conclusions

    As I already said at the beginning, my experiments are not flawless and it is not worth relying solely on the results obtained during them, because, despite the speed file_get_contents() in my situation, there are times when it is much more convenient and efficient to use the other PHP file parsers I have given.

    In addition, do not forget that PHP itself is a synchronous programming language, i.e. all server operations occur sequentially without the ability to configure their parallel execution, including on different cores of the server processor.

    Consequently, the execution time of operations written in PHP code can be influenced by a number of factors, among which the main one is the kernel load at the time the PHP application is running.

    I especially felt this during experiments when the same PHP file parser worked in 9, then in 12, and then again in 9 seconds on three consecutive iterations due to the banal launch of Windows Explorer during the second case, which, of course, , also requires server resources.

    Taking these features into account, I conducted experiments almost simultaneously, one after another, with the same set of programs running, so as not to waste server hardware resources.

    Therefore, in the future, when conducting similar experiments with PHP constructs, proceed in the same way, because this is, in fact, the only way to bring experiments to a level playing field.

    If you work with asynchronous server-side languages ​​(C#, Java) or technologies (Node.js, for example), then, if possible, for experiments, create a separate thread that will run on a dedicated processor core.

    Well, if you can’t find a completely unused core (which is not surprising given the level of modern software), then you can at least find the lightest loaded one, or at least one with a static load that does not change over time.

    To summarize, I want to say that the code fragments presented in the article can be used not only for parsing text files in PHP, but are also perfect for other formats, for example, for parsing CSV files.

    Write your feedback, both positive and negative, in the comments under the article - I need any of your opinions for further development :)

    See you again! 🙂

    P.S.: if you need a website or need to make changes to an existing one, but there is no time or desire for this, I can offer my services.

    More than 5 years of experience professional website development. Work with PHP, OpenCart, WordPress, Laravel, Yii, MySQL, PostgreSQL, JavaScript, React, Angular and other web development technologies.

    Experience in developing projects at various levels: landing pages, corporate websites, Online stores, CRM, portals. Including support and development HighLoad projects. Send your applications by email [email protected].

    The task of parsing and processing the necessary information from a third-party site confronts a web developer quite often and for a variety of reasons: in this way you can fill your project with content, dynamically load some information, and so on.

    In such cases, the programmer is faced with the question: which of dozens of libraries to choose? In this article, we tried to consider the most popular options and choose the best one.

    Regular Expressions

    Even though “regular ones” are the first thing that comes to mind, you shouldn’t use them for real projects.

    Yes, regular expressions do the best job with simple tasks, but their use becomes much more difficult when you need to parse a large and complex piece of HTML code, which, moreover, does not always match any specific pattern and may generally contain syntax errors.

    Instead of “finishing” your regular expression with every slightest change in the code, we recommend using the tools below - it’s simpler, more convenient, and more reliable.

    XPath and DOM

    htmlSQL

    If you don't use PHP, you can check out this short list of similar tools for other programming languages.