Checking the occurrence of a substring in a php string. Finding a substring in a string using PHP


Finds the first occurrence of a character in a string.

Syntax:

String strchr(string haystack, string needle)

This function works identical to the strstr() function

Determines the absence of leading characters in a string.
Syntax:

Int strcspn(string str1, string str2)

The strspn() function returns the length of the initial fragment of the string str1, which consists entirely of characters other than those found in the string str2.

strpbrk()

Search a string for any character from a given set (PHP5)

Syntax:

String strpbrk (string haystack, string char_list)

strpbrk() searches the haystack string for characters in the char_list and returns the string starting at the position where the character was found (or FALSE if the character was not found). The char_list parameter is case sensitive.

$text = "This is a Simple text.";

echo strpbrk($text, "mi"); // Will produce "is is a Simple text." because the character "i" will occur first

echo strpbrk($text, "S");// Will produce "Simple text.", because characters are case sensitive
?>

Finding the first occurrence of a substring in a string.
Syntax:

String strstr(string haystack, string needle)

The strstr() function returns the portion of the string specified in the haystack parameter, starting with the first fragment specified in the needle parameter and ending with the end.

$email = " [email protected]";
$domain = strstr($email, "@");
// or $domain = strstr($email, ord("@"))
echo $domain;
// will display @mail.ru

Finding the first occurrence of a substring, insensitive to case.
Syntax:

String stristr(string haystack, string needle)

The stristr() function returns the portion of the string specified in the haystack parameter, starting with the first fragment specified in the needle parameter and ending with the end.
If unsuccessful, returns false.
This function is case insensitive.
If needle is not a string, then the value is converted to an integer and used as the code for the searched character.

Finding the last occurrence of a substring.
Syntax:

String strrchr(string haystack, string needle)

The strrchr() function returns the portion of the string specified in the haystack parameter, starting with the last fragment specified in the needle parameter and ending.
If unsuccessful, returns false.
This function is case sensitive.
If needle is not a string, then the value is converted to an integer and used as the code for the searched character.

// get the last directory in $PATH
$dir = substr(strrchr($PATH, ":"), 1);
// and here we get everything after the last line break$text = "text 1nText2nText3";
echo substr(strrchr($text, 10), 1);

Finds the position of the first occurrence of a substring in given string.
Syntax:

Int strpos(string where, string what [, int fromwhere])

The strpos() function tries to find the substring what in the string were and, if successful, returns the position (index) of this substring in the string.
The first character of the line has index 0. Optional parameter fromwhere can be specified if the search needs to be carried out not from the beginning of the line, but from some other position. In this case, this position should be passed to fromwhere. If the substring could not be found, the function returns false.

If(strpos($text, "a")===false) echo "Not found!";
// Check: three equal signs

Finds the position of the first occurrence of a substring in a given string, case insensitive.
Syntax:

Int stripos(string where, string what [, int fromwhere])

The stripos() function tries to find the substring what in the string were and, if successful, returns the position (index) of this substring in the string.
Unlike strpos(), this function is case-insensitive. The first character of the line has index 0.
The optional fromwhere parameter can be specified if the search needs to be carried out not from the beginning of the line, but from some other position.
In this case, this position should be passed to fromwhere. If the substring could not be found, the function returns false.
If the what parameter is not a string, then its value is converted to an integer and used as the code for the character being searched for.

$mystring1 = "xyz";
$mystring2 = "ABC";

$pos1 = stripos($mystring1, $findme);
$pos2 = stripos($mystring2, $findme);

// Of course, "a" is not in "xyz"
if ($pos1 === false) (
echo "String "$findme" not found in string "$mystring1"";
}

// Note that === is used. Using == will not give the correct result
// result, since "a" is in position zero.if ($pos2 !== false) (
echo "Found "$findme" in "$mystring2" at position $pos2";
}
?>

Note: The stripos() function can be used to search for data in binary form.
Support: PHP 5

Finds the last position in the given string that contains the given fragment.
Syntax:

Int strrpos(string where, string what)

This function searches the where string for the last position in which the what character occurred (if what is
string of several characters, then only the first of them is detected, the rest do not play any role).

If the character you are looking for is the first one in the string or is not there at all, the function will return 0.

If the searched character is not found, returns false.

substr_count

Finds the number of occurrences of a fragment in a string.
Syntax:

Int substr_count(string where, string what)

The substr_count() function returns the number of what fragments present in the where string.

Echo substr_count("www.spravkaweb.ru", ".");
// Prints 3

Determines the presence of leading characters in a string.
Syntax:

Int strspn(string str1, string str2)

The strspn() function returns the length of the initial fragment of the string str1, consisting entirely of characters that are in the string str2.

Echo strspn("www.spravkaweb.ru", "abc");
// Prints 3

Now we will look at examples of what an algorithm for finding a substring in a string might look like. The examples will be based on the functions of standard libraries, because it is in such functions that all the convenience of writing programs is manifested. But the classic analysis of the algorithm, based on cycles and comparisons, is also quite remarkable. Therefore, we will look at it in the same lesson.

The algorithm itself is very simple in principle. There are two lines. For example "Hello world" And "lo"

We will work in two cycles:

    1. The first one will iterate over the entire string and look for the location first letter search string ( "lo").
    2. The second, starting from the found position of the first letter, is to check which letters come after it and how many of them coincide in a row.

Let's illustrate searching for a substring in a string:

During the first two iterations of the loop, the letters being compared will not match (highlighted in red). On the third iteration, the searched letter (the first character of the search word) coincided with the character in the line where the search occurs. With such a coincidence, the second cycle is activated.

It is designed to count the number of characters after the first in the search string that will match the characters in the source string. If one of the following characters does not match, the loop ends. There is no point in running the loop in vain after the first mismatch, since it is already clear that what you are looking for is not there.

On the third iteration, only the first character of the desired string matched, but the second did not match. The first cycle will have to continue working. The fourth iteration gives the necessary results - all the characters of the search string match part of the source string. And if all the characters match, the substring has been found. The work of the algorithm can be completed.

Let's see what the classic code for searching a substring in a string looks like in C++:

Finding a substring in a string

#include // Function for searching for a substring in a string // + searching for the position from which the substring begins int pos(char *s, char *c, int n) ( int i, j; // Counters for loops int lenC, lenS; // String lengths //Find the sizes of the source and target strings for (lenC = 0; c; lenC++); for (lenS = 0; s; lenS++); for (i = 0; i<= lenS - lenC; i++) // Пока есть возможность поиска { for (j = 0; s == c[j]; j++); // Проверяем совпадение посимвольно // Если посимвольно совпадает по длине искомого // Вернем из функции номер ячейки, откуда начинается совпадение // Учитывать 0-терминатор ("\0") if (j - lenC == 1 && i == lenS - lenC && !(n - 1)) return i; if (j == lenC) if (n - 1) n--; else return i; } //Иначе вернем -1 как результат отсутствия подстроки return -1; } int main() { char *s = "parapapa"; char *c = "pa"; int i, n = 0; for (i = 1; n != -1; i++) { n = pos(s, c, i); if (n >= 0) std::cout<< n << std:: endl; } }

#include

// Function to find a substring in a string

// + search for the position where the substring begins

int pos (char * s, char * c, int n)

int i, j; // Counters for loops

int lenC, lenS; // String lengths

//Find the sizes of the source and desired strings

for (i = 0 ; i<= lenS - lenC ; i ++ ) // While searching is possible

for (j = 0; s [ i + j ] == c [ j ] ; j ++ ) ; // Check the match character by character

// If character by character matches the length of the searched

// Return from the function the number of the cell where the match begins

// Consider the 0-terminator ("\0")

if (j - lenC == 1 && i == lenS - lenC && ! (n - 1) ) return i ;

if (j == lenC )

if (n - 1 ) n -- ;

else return i ;

//Otherwise we return -1 as a result of the absence of a substring

return - 1 ;

int main()

char * s = "parapapa" ;

char * c = "pa" ;

int i, n = 0;

n = pos(s, c, i);

if (n >= 0 )

std::cout<< n << std :: endl ;

Two loops each perform their own task. One stomps along the line in the hope of finding the “head” of the searched word (the first character). The second one finds out whether after the found “head” there is a “body” of the one being sought. Moreover, it checks whether this “body” is at the end of the line. Those. Is the length of the found word one greater than the length of the searched string, taking into account that the null terminator ( "\0" ).

We see that the program has found the beginning of the substring pa in character array cells with index 0 and 4. But why? After all, in the word parapapa 3 such substrings. It's all about "\0" .

More about this

For example lines: "Remember Harry room room" And "room" actually look like "Remember Harry room room\0" And "room\0". Where "\0" , a character with code 0, which indicates that the line has ended. By the way, it is precisely this approach that allows you to write cycles such as:

for (lenC = 0; c; lenC++); for (lenS = 0; s; lenS++);

for (lenC = 0; c [ lenC ]; lenC ++ ) ;

for (lenS = 0 ; s [ lenS ] ; lenS ++ ) ;

Here c And s

If we want to find a word room 5

The fact is that C-string characters are stored in a character array. Each line is characterized by the so-called ASCIIZ property. This abbreviation literally translates as “a string that ends with a character with a code equal to zero” - ask-zero.

The catch is that if what you are looking for is at the very end of the line, you will have to take this zero into account. It is also part of the string, and with this algorithm it also coincides with the end of the desired string.

For example, the lines: and actually look like and . Where , a character with code 0, which indicates that the line has ended. By the way, it is precisely this approach that allows you to write cycles such as:

Here c And s are compared to a null value, and are conveniently read as “Increment the counter as long as there is a (non-blank) character in the string.” The last symbol, zero, will be considered empty.

If we want to find a word room, standing in the middle of a word, we need to compare only 4 characters, but if suddenly what we are looking for occurs only at the end, we need to compare not 4 characters, but... 5 ! Or check if there is a null terminator after it. There's nothing complicated about it. You just need to get used to this line.

In general, the meaning of the algorithm itself ends here. There are no more complications except the zero at the end of the line. However, you should pay attention to the multiplicity of the search. What if we need to find multiple positions in a string?

How many times does the search word appear in the line and in what places? This is exactly what the third parameter is designed to control - int n – number of occurrences in the line. If you put one there, it will find the first match of what you are looking for. If it is a two, it will force the first loop to skip the first one found and look for the second. If it’s a three, look for the third and so on. With each search word found, this occurrence counter decreases by one. This allows us to describe the search in a loop:

for (i = 1; n != -1; i++) ( n = pos(s, c, i); if (n >= 0) std:: cout<< n << std:: endl; }

for (i = 1 ; n != - 1 ; i ++ )

n = pos(s, c, i);

if (n >= 0 )

std::cout<< n << std :: endl ;

That is, find the first, second, third, fourth match... Until the function returns -1 , which will indicate the absence of the Nth searched item in the line.

Now, for comparison, searching for a substring in a C++ string with a header string.

Finding a substring in a C++ string

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.

Automatic removal of html tags from a string

When using user-filled forms, sometimes you need to remove all unnecessary tags. This task is 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 place a URL in a comment form on a 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));







2024 gtavrl.ru.