What are the different types of string functions in php?

A string is a sequence of characters, like "Hello world!".

PHP String Functions

In this chapter we will look at some commonly used functions to manipulate strings.

strlen[] - Return the Length of a String

The PHP strlen[] function returns the length of a string.

Example

Return the length of the string "Hello world!":

Try it Yourself »

str_word_count[] - Count Words in a String

The PHP str_word_count[] function counts the number of words in a string.

Example

Count the number of word in the string "Hello world!":

Try it Yourself »

strrev[] - Reverse a String

The PHP strrev[] function reverses a string.

Example

Reverse the string "Hello world!":

Try it Yourself »

strpos[] - Search For a Text Within a String

The PHP strpos[] function searches for a specific text within a string. If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.

Example

Search for the text "world" in the string "Hello world!":

Try it Yourself »

Tip: The first character position in a string is 0 [not 1].

str_replace[] - Replace Text Within a String

The PHP str_replace[] function replaces some characters with some other characters in a string.

Example

Replace the text "world" with "Dolly":

Try it Yourself »

Complete PHP String Reference

For a complete reference of all string functions, go to our complete PHP String Reference.

The PHP string reference contains description and example of use, for each function!

PHP Exercises



Table of Contents

  • addcslashes — Quote string with slashes in a C style
  • addslashes — Quote string with slashes
  • bin2hex — Convert binary data into hexadecimal representation
  • chop — Alias of rtrim
  • chr — Generate a single-byte string from a number
  • chunk_split — Split a string into smaller chunks
  • convert_cyr_string — Convert from one Cyrillic character set to another
  • convert_uudecode — Decode a uuencoded string
  • convert_uuencode — Uuencode a string
  • count_chars — Return information about characters used in a string
  • crc32 — Calculates the crc32 polynomial of a string
  • crypt — One-way string hashing
  • echo — Output one or more strings
  • explode — Split a string by a string
  • fprintf — Write a formatted string to a stream
  • get_html_translation_table — Returns the translation table used by htmlspecialchars and htmlentities
  • hebrev — Convert logical Hebrew text to visual text
  • hebrevc — Convert logical Hebrew text to visual text with newline conversion
  • hex2bin — Decodes a hexadecimally encoded binary string
  • html_entity_decode — Convert HTML entities to their corresponding characters
  • htmlentities — Convert all applicable characters to HTML entities
  • htmlspecialchars_decode — Convert special HTML entities back to characters
  • htmlspecialchars — Convert special characters to HTML entities
  • implode — Join array elements with a string
  • join — Alias of implode
  • lcfirst — Make a string's first character lowercase
  • levenshtein — Calculate Levenshtein distance between two strings
  • localeconv — Get numeric formatting information
  • ltrim — Strip whitespace [or other characters] from the beginning of a string
  • md5_file — Calculates the md5 hash of a given file
  • md5 — Calculate the md5 hash of a string
  • metaphone — Calculate the metaphone key of a string
  • money_format — Formats a number as a currency string
  • nl_langinfo — Query language and locale information
  • nl2br — Inserts HTML line breaks before all newlines in a string
  • number_format — Format a number with grouped thousands
  • ord — Convert the first byte of a string to a value between 0 and 255
  • parse_str — Parses the string into variables
  • print — Output a string
  • printf — Output a formatted string
  • quoted_printable_decode — Convert a quoted-printable string to an 8 bit string
  • quoted_printable_encode — Convert a 8 bit string to a quoted-printable string
  • quotemeta — Quote meta characters
  • rtrim — Strip whitespace [or other characters] from the end of a string
  • setlocale — Set locale information
  • sha1_file — Calculate the sha1 hash of a file
  • sha1 — Calculate the sha1 hash of a string
  • similar_text — Calculate the similarity between two strings
  • soundex — Calculate the soundex key of a string
  • sprintf — Return a formatted string
  • sscanf — Parses input from a string according to a format
  • str_contains — Determine if a string contains a given substring
  • str_ends_with — Checks if a string ends with a given substring
  • str_getcsv — Parse a CSV string into an array
  • str_ireplace — Case-insensitive version of str_replace
  • str_pad — Pad a string to a certain length with another string
  • str_repeat — Repeat a string
  • str_replace — Replace all occurrences of the search string with the replacement string
  • str_rot13 — Perform the rot13 transform on a string
  • str_shuffle — Randomly shuffles a string
  • str_split — Convert a string to an array
  • str_starts_with — Checks if a string starts with a given substring
  • str_word_count — Return information about words used in a string
  • strcasecmp — Binary safe case-insensitive string comparison
  • strchr — Alias of strstr
  • strcmp — Binary safe string comparison
  • strcoll — Locale based string comparison
  • strcspn — Find length of initial segment not matching mask
  • strip_tags — Strip HTML and PHP tags from a string
  • stripcslashes — Un-quote string quoted with addcslashes
  • stripos — Find the position of the first occurrence of a case-insensitive substring in a string
  • stripslashes — Un-quotes a quoted string
  • stristr — Case-insensitive strstr
  • strlen — Get string length
  • strnatcasecmp — Case insensitive string comparisons using a "natural order" algorithm
  • strnatcmp — String comparisons using a "natural order" algorithm
  • strncasecmp — Binary safe case-insensitive string comparison of the first n characters
  • strncmp — Binary safe string comparison of the first n characters
  • strpbrk — Search a string for any of a set of characters
  • strpos — Find the position of the first occurrence of a substring in a string
  • strrchr — Find the last occurrence of a character in a string
  • strrev — Reverse a string
  • strripos — Find the position of the last occurrence of a case-insensitive substring in a string
  • strrpos — Find the position of the last occurrence of a substring in a string
  • strspn — Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask
  • strstr — Find the first occurrence of a string
  • strtok — Tokenize string
  • strtolower — Make a string lowercase
  • strtoupper — Make a string uppercase
  • strtr — Translate characters or replace substrings
  • substr_compare — Binary safe comparison of two strings from an offset, up to length characters
  • substr_count — Count the number of substring occurrences
  • substr_replace — Replace text within a portion of a string
  • substr — Return part of a string
  • trim — Strip whitespace [or other characters] from the beginning and end of a string
  • ucfirst — Make a string's first character uppercase
  • ucwords — Uppercase the first character of each word in a string
  • utf8_decode — Converts a string from UTF-8 to ISO-8859-1, replacing invalid or unrepresentable characters
  • utf8_encode — Converts a string from ISO-8859-1 to UTF-8
  • vfprintf — Write a formatted string to a stream
  • vprintf — Output a formatted string
  • vsprintf — Return a formatted string
  • wordwrap — Wraps a string to a given number of characters

lrirwin at alum dot wustl dot edu

1 year ago

I'm converting 30 year old code and needed a string TAB function:

  //tab function similar to TAB used in old BASIC languages
  //though some of them did not truncate if the string were
  //longer than the requested position
  function tab[$instring="",$topos=0]{
    if[strlen[$instring]

[tab!]

17 years ago

//
// string strtrmvistl[  string str, [int maxlen = 64],
//                      [bool right_justify = false],
//                      [string delimter = "
\n"]]
//
// splits a long string into two chunks [a start and an end chunk]
// of a given maximum length and seperates them by a given delimeter.
// a second chunk can be right-justified within maxlen.
// may be used to 'spread' a string over two lines.
//

function strtrmvistl[$str, $maxlen = 64, $right_justify = false, $delimter = "
\n"] {
    if[[$len = strlen[$str = chop[$str]]] > [$maxlen = max[$maxlen, 12]]] {
        $newstr = substr[$str, 0, $maxlen - 3];

        if[$len > [$maxlen - 3]] {
            $endlen = min[[$len - strlen[$newstr]], $maxlen - 3];
            $newstr .= "..." . $delimter;

            if[$right_justify]
                $newstr .= str_pad['', $maxlen - $endlen - 3, ' '];

            $newstr .= "..." . substr[$str, $len - $endlen];
        }

        return[$newstr];
    }

    return[$str];
}

t0russ at gmail dot com

17 years ago

to kristin at greenaple dot on dot ca:
thanx for sharing.
your function in recursive form proved to be slightly faster and it returns false [as it should] when the character is not found instead of number 0:

str at maphpia dot com

9 years ago

I was looking for a function to find the common substring in 2 different strings. I tried both the mb_string_intersect and string_intersect functions listed here but didn't work for me. I found the algorithm at //en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_substring#PHP so here I post you the function



The code doesn't need to know anything about the number of elements being cycled through. That way you won't have to tracking down all the code when changing the number of colors or the color values.

Anonymous

17 years ago

In response to hackajar yahoo com,

No string-to-array function exists because it is not needed. If you reference a string with an offset like you do with an array, the character at that offset will be return. This is documented in section III.11's "Strings" article under the "String access and modification by character" heading.

andy a t onesandzeros d o t biz

17 years ago

I use these little doo-dads quite a bit. I just thought I'd share them and maybe save someone a little time. No biggy. :]

// returns true if $str begins with $sub
function beginsWith[ $str, $sub ] {
    return [ substr[ $str, 0, strlen[ $sub ] ] == $sub ];
}

// return tru if $str ends with $sub
function endsWith[ $str, $sub ] {
    return [ substr[ $str, strlen[ $str ] - strlen[ $sub ] ] == $sub ];
}

// trims off x chars from the front of a string
// or the matching string in $off is trimmed off
function trimOffFront[ $off, $str ] {
    if[ is_numeric[ $off ] ]
        return substr[ $str, $off ];
    else
        return substr[ $str, strlen[ $off ] ];
}

// trims off x chars from the end of a string
// or the matching string in $off is trimmed off
function trimOffEnd[ $off, $str ] {
    if[ is_numeric[ $off ] ]
        return substr[ $str, 0, strlen[ $str ] - $off ];
    else
        return substr[ $str, 0, strlen[ $str ] - strlen[ $off ] ];
}

kristin at greenapple dot on dot ca

17 years ago

I really searched for a function that would do this as I've seen it in other languages but I couldn't find it here. This is particularily useful when combined with substr[] to take the first part of a string up to a certain point.

strnpos[] - Find the nth position of needle in haystack.



Example: Give me everything up to the fourth occurance of '/'.



Returns: /home/username/www

Use this example with the server variable $_SERVER['SCRIPT_NAME'] as the haystack and you can self-discover a document's root directory for the purposes of locating global files automatically!

SteveRusin

16 years ago

The functions below:

function beginsWith[ $str, $sub ]
function endsWith[ $str, $sub ]

Are correct, but flawed.  You'd need to use the === operator instead:

function beginsWith[ $str, $sub ] {
   return [ substr[ $str, 0, strlen[ $sub ] ] === $sub ];
}
function endsWith[ $str, $sub ] {
   return [ substr[ $str, strlen[ $str ] - strlen[ $sub ] ] === $sub ];
}

Otherwise, endsWith would return "foobar.0" ends with ".0" as well as "0" or "00" or any amount of zeros because numerically .0 does equal 0.

mike "eyes" moe

15 years ago

Here is a truly random string generator it uses the most common string functions it will work on anywhere.

admin at rotarymulundeast dot org

16 years ago

Here's an easier way to find nth...

function nth[$numbex]{
  if [$numbex%10 == 1 && $numbex%100 != 11] $sth='st';
  elseif [$numbex%10 == 2 && $numbex%100 != 12] $sth='nd';
  elseif [$numbex%10 == 3 && $numbex%100 != 13] $sth='rd';
  else $sth = 'th';
  return $sth;
}

there is is no need to check if the user has entered a non-integer as we may be using this function for expressing variables as well eg. ith value of x , nth root of z ,etc...

m

15 years ago

Regarding the code for the function beginsWith[$str, $sub], I found that it has problems when only one character is present after the string searched for. I found that this works better instead:

james dot d dot baker at gmail dot com

17 years ago

Chủ Đề