Как найти последнее вхождение строки

(PHP 4, PHP 5, PHP 7, PHP 8)

strrchrНаходит последнее вхождение символа в строке

Описание

strrchr(string $haystack, string $needle): string|false

Список параметров

haystack

Строка, в которой производится поиск

needle

Если needle состоит более чем из
одного символа, используется только первый символ. Это поведение
отличается от strstr().

До PHP 8.0.0, если параметр needle не является строкой,
он преобразуется в целое число и трактуется как код символа.
Это поведение устарело с PHP 7.3.0, и полагаться на него крайне не рекомендуется.
В зависимости от предполагаемого поведения,
параметр needle должен быть либо явно приведён к строке,
либо должен быть выполнен явный вызов chr().

Возвращаемые значения

Функция возвращает фрагмент строки, или false, если подстрока
needle не найдена.

Список изменений

Версия Описание
8.0.0 Передача целого числа (int) в needle больше не поддерживается.
7.3.0 Передача целого числа (int) в needle объявлена устаревшей.

Примеры

Пример #1 Пример использования strrchr()


<?php
// получить последнюю директорию из $PATH
$dir = substr(strrchr($PATH, ":"), 1);// получить все после последнего перевода строки
$text = "Line 1nLine 2nLine 3";
$last = substr(strrchr($text, 10), 1 );
?>

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • strstr() — Находит первое вхождение подстроки
  • strrpos() — Возвращает позицию последнего вхождения подстроки в строке

matthewkastor at live dot com

12 years ago


<?php

/**

* Removes the preceeding or proceeding portion of a string

* relative to the last occurrence of the specified character.

* The character selected may be retained or discarded.

*

* Example usage:

* <code>

* $example = 'http://example.com/path/file.php';

* $cwd_relative[] = cut_string_using_last('/', $example, 'left', true);

* $cwd_relative[] = cut_string_using_last('/', $example, 'left', false);

* $cwd_relative[] = cut_string_using_last('/', $example, 'right', true);

* $cwd_relative[] = cut_string_using_last('/', $example, 'right', false);

* foreach($cwd_relative as $string) {

*     echo "$string <br>".PHP_EOL;

* }

* </code>

*

* Outputs:

* <code>

* http://example.com/path/

* http://example.com/path

* /file.php

* file.php

* </code>

*

* @param string $character the character to search for.

* @param string $string the string to search through.

* @param string $side determines whether text to the left or the right of the character is returned.

* Options are: left, or right.

* @param bool $keep_character determines whether or not to keep the character.

* Options are: true, or false.

* @return string

*/

function cut_string_using_last($character, $string, $side, $keep_character=true) {

   
$offset = ($keep_character ? 1 : 0);

   
$whole_length = strlen($string);

   
$right_length = (strlen(strrchr($string, $character)) - 1);

   
$left_length = ($whole_length - $right_length - 1);

    switch(
$side) {

        case
'left':

           
$piece = substr($string, 0, ($left_length + $offset));

            break;

        case
'right':

           
$start = (0 - ($right_length + $offset));

           
$piece = substr($string, $start);

            break;

        default:

           
$piece = false;

            break;

    }

    return(
$piece);

}

?>

sekati at gmail dot com

17 years ago


just a small addition to carlos dot lage at gmail dot com note which makes it a bit more useful and flexible:

<?php
// return everything up to last instance of needle
// use $trail to include needle chars including and past last needle
function reverse_strrchr($haystack, $needle, $trail) {
    return
strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) + $trail) : false;
}
// usage:
$ns = (reverse_strrchr($_SERVER["SCRIPT_URI"], "/", 0));
$ns2 = (reverse_strrchr($_SERVER["SCRIPT_URI"], "/", 1));
echo(
$ns . "<br>" . $ns2);
?>


dchris1 at bigpond dot net dot au

19 years ago


The function provided by marcokonopacki at hotmail dot com isn't really a reverse-version of strrchr(), rather a reverse version of strchr(). It returns everything from the start of $haystack up to the FIRST instance of the $needle. This is basically a reverse of the behavior which you expect from strchr(). A reverse version of strrchr() would return everything in $haystack up to the LAST instance of $needle, eg:

<?php
// reverse strrchr() - PHP v4.0b3 and above
function reverse_strrchr($haystack, $needle)
{
   
$pos = strrpos($haystack, $needle);
    if(
$pos === false) {
        return
$haystack;
    }
    return
substr($haystack, 0, $pos + 1);
}
?>

Note that this function will need to be modified slightly to work with pre 4.0b3 versions of PHP due to the return type of strrpos() ('0' is not necessarily 'false'). Check the documentation on strrpos() for more info.

A function like this can be useful for extracting the path to a script, for example:

<?
$string = "/path/to/the/file/filename.php";

echo reverse_strrchr($string, '/'); // will echo "/path/to/the/file/"
?>


readless at gmx dot net

16 years ago


to: repley at freemail dot it

the code works very well, but as i was trying to cut script names (e.g.: $_SERVER["SCRIPT_NAME"] => /index.php, cut the string at "/" and return "index.php") it returned nothing (false). i've modified your code and now it works also if the needle is the first char.
- regards from germany

<?php
//strxchr(string haystack, string needle [, bool int leftinclusive [, bool int rightinclusive ]])
function strxchr($haystack, $needle, $l_inclusive = 0, $r_inclusive = 0){
   if(
strrpos($haystack, $needle)){
      
//Everything before last $needle in $haystack.
      
$left substr($haystack, 0, strrpos($haystack, $needle) + $l_inclusive);//Switch value of $r_inclusive from 0 to 1 and viceversa.
      
$r_inclusive = ($r_inclusive == 0) ? 1 : 0;//Everything after last $needle in $haystack.
      
$right substr(strrchr($haystack, $needle), $r_inclusive);//Return $left and $right into an array.
      
return array($left, $right);
   } else {
       if(
strrchr($haystack, $needle)) return array('', substr(strrchr($haystack, $needle), $r_inclusive));
       else return
false;
   }
}
?>


Primo Anderson Do S?tio

17 years ago


$filename = 'strrchr_test.php';
print strrchr( $filename, '.' );

Result:
.php

$other_filename = 'strrchr_test.asp.php';
print  strrchr( $other_filename, '.' );

Result:
.php


freakinunreal at hotmail dot com

17 years ago


to marcokonopacki at hotmail dot com.

I had to make a slight change in your function for it to return the complete needle inclusive.

// Reverse search of strrchr.
function strrrchr($haystack,$needle)
{

   // Returns everything before $needle (inclusive).
   //return substr($haystack,0,strpos($haystack,$needle)+1);
   // becomes
   return substr($haystack,0,strpos($haystack,$needle)+strlen($needle));
}

Note: the +1 becomes +strlen($needle)

Otherwise it only returns the first character in needle backwards.


marcokonopacki at hotmail dot com

20 years ago


<?

// Reverse search of strrchr.
function strrrchr($haystack,$needle)
{

    // Returns everything before $needle (inclusive).
    return substr($haystack,0,strpos($haystack,$needle)+1);

    }

$string = "FIELD NUMBER(9) NOT NULL";

echo strrrchr($string,")"); // Will print FIELD (9)

?>


carlos dot lage at gmail dot com

18 years ago


I used dchris1 at bigpond dot net dot au 's reverse strrchr and reduced it to one line of code and fixed it's functionality - the real strrchr() returns FALSE if the needle is not found, not the haystack :)

<?php
// reverse strrchr()
function reverse_strrchr($haystack, $needle)
{
                return
strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
}
?>


andfarm at thibs dot menloschool dot org

20 years ago


strrchr is also very useful for finding the extension of a file. For example:

$ext = strrchr($filename, ".");

and $ext will contain the extension of the file, including a ".", if the file has an extension, and FALSE if the file has no extension. If the file has multiple extensions, such as "evilfile.jpg.vbs", then this construction will just return the last extension.


alex_bb23 at yahoo.co.uk

5 years ago


I think that a good way (I don't know if is the best one) to extract a portion from a string:
<?php

$image

= "image.name.jpg";
// get file extension
preg_replace("/.*.(.*)$/", "$1", $last);
// will result: jpg?>

Is faster that substr(strrchr...

Sometimes, while working with strings, we need to find if a substring exists in the string. This problem is quite common and its solution has been discussed many times before. The variation of getting the last occurrence of the string is discussed here. Let’s discuss certain ways in which we can find the last occurrence of substring in string in Python. 

Using rindex() to find last occurrence of substring

rindex() method returns the last occurrence of the substring if present in the string. The drawback of this function is that it throws the exception if there is no substring in the string and hence breaks the code. 

Python3

test_string = "GfG is best for CS and also best for Learning"

tar_word = "best"

print("The original string : " + str(test_string))

res = test_string.rindex(tar_word)

print("Index of last occurrence of substring is : " + str(res))

Output

The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28

Using rfind() to find last occurrence of substring

rfind() is the alternate method to perform this task. The advantage that this function offers better than the above method is that, this function returns a “-1” if a substring is not found rather than throwing the error. 

Python3

test_string = "GfG is best for CS and also best for Learning"

tar_word = "best"

print("The original string : " + str(test_string))

res = test_string.rfind(tar_word)

print("Index of last occurrence of substring is : " + str(res))

Output

The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28

Using lambda() with rlocate() function

Here we are using the more_itertools library that provides us with rlocate() function that helps us to find the last occurrence of the substring in the given string.

Python3

import more_itertools as m

test_string = "GfG is best for CS and also best for Learning"

tar_word = "best"

pred = lambda *x: x == tuple(tar_word)

print("The original string : " +

      str(test_string))

res = next(m.rlocate(test_string, pred=pred,

                     window_size=len(tar_word)))

print("Index of last occurrence of substring is : " +

      str(res))

Output:

The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28

Using find() and replace() methods

Python3

test_string = "GfG is best for CS and also best for Learning"

tar_word = "best"

print("The original string : " + str(test_string))

x=test_string.count(tar_word)

i=1

while(i<x):

    test_string=test_string.replace(tar_word,"*"*len(tar_word),1)

    i+=1

res=test_string.find(tar_word)

print("Index of last occurrence of substring is : " + str(res))

Output

The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28

Time Complexity: O(n), where n is length of test_string.

Auxiliary Space: O(1)

Using the re module:

The re (regular expression) module in Python allows you to search for patterns in strings. In this approach, we use the finditer function from the re module to find all occurrences of the substring in the string. The finditer function returns an iterator yielding MatchObject instances that have information about the search, such as the start and end indices of the match.

We can then use a for loop to iterate through the matches and keep track of the index of the last occurrence by updating the last_occurrence variable whenever we find a match. Finally, we print the index of the last occurrence.

Python3

import re

test_string = "GfG is best for CS and also best for Learning"

tar_word = "best"

matches = re.finditer(tar_word, test_string)

last_occurrence = -1

for match in matches:

    last_occurrence = match.start()

print("Index of last occurrence of substring is:", last_occurrence)

Output

Index of last occurrence of substring is: 28

Time complexity: O(n), where n is the length of the string
Auxiliary Space : O(n)

Using reversed() function and index()

Step-by-step approach:

  1. Reverse the test_string and tar_word
  2. Use the index() method to get the first occurrence of the reversed tar_word in the reversed test_string.
  3. Calculate the index of the last occurrence of the tar_word by subtracting the index from the length of the test_string and the length of the tar_word.

Python3

test_string = "GfG is best for CS and also best for Learning"

tar_word = "best"

res = len(test_string) - test_string[::-1].index(tar_word[::-1]) - len(tar_word)

print("Index of last occurrence of substring is : " + str(res))

Output

Index of last occurrence of substring is : 28

Time complexity: O(n) where n is the length of the string
Space complexity: O(1)

Using the numpy:

Algorithm:

  1. Initialize the test string and target word.
  2. Create an empty numpy array to store the indices of all occurrences of the target word.
  3. Iterate over all possible substrings of length equal to the length of the target word in the test string. For each substring, check if it matches the target word or not. If the substring matches the target word, append the index of the first character of the substring to the numpy array.
  4. Check if any occurrences of the target word were found or not. If the numpy array is not empty, set the result to be the last element of the array (i.e., the index of the last occurrence of the target word in the test string). Otherwise, set the result to -1 (indicating that the target word was not found in the test string).
  5. Print the original string and the index of the last occurrence of the target word (or -1 if the target word was not found).

Below is the implementation of the above approach:

Python3

import numpy as np

test_string = "GfG is best for CS and also best for Learning"

tar_word = "best"

indices = np.array([i for i in range(len(test_string)-len(tar_word)+1)

                    if test_string[i:i+len(tar_word)] == tar_word])

if indices.size > 0:

    res = indices[-1]

else:

    res = -1

print("The original string : " + str(test_string))

print("Index of last occurrence of substring is : " + str(res))

Output:

The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28

Time Complexity: O(n * m), where n is the length of the test string and m is the length of the target word. This is because the list comprehension iterates over all possible substrings of length m in the test string, which takes O(n * m) time in the worst case.

Space Complexity: O(k), where k is the number of occurrences of the target word in the test string. This is because the indices of all occurrences of the target word are stored in a numpy array, which takes O(k) space. The rest of the variables used in the code take constant space.

Using rpartition() method

  • Define the string and target word to find last occurrence of substring.
  • Use the rpartition() method to split the string at the last occurrence of the target word.
  • If the length of split list is 1, print that the substring was not found in the string.
  • Otherwise, calculate the index of the last occurrence of the target word using the length of the original string, the length of the third element in the split list (which contains the characters after the last occurrence of the target word), and the length of the target word.
  • Print the index of the last occurrence of the target word.

Python3

test_string = "GfG is best for CS and also best for Learning"

tar_word = "best"

print("The original string : " + str(test_string))

split_list = test_string.rpartition(tar_word)

if len(split_list) == 1:

   print("Substring not found in string")

else:

   res = len(test_string) - len(split_list[2]) - len(tar_word)

   print("Index of last occurrence of substring is : " + str(res))

Output

The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28

Time Complexity: O(n), where n is the length of the input string.

Auxiliary Space: O(1), as no extra is used.

Last Updated :
17 Apr, 2023

Like Article

Save Article

str.index

Чтобы распознать случаи: 0, 1, 2+ вхождений без явных циклов, s.count('f') метода, очевидная альтернатива s.find() методу из вопроса — это s.index():

#!/usr/bin/env python3

s = input()
count = len(s) - len(s.replace('f', ''))
if count == 0:
    pass
elif count == 1:
    print(s.index('f'))
else: # count > 1
    print(s.index('f'), s.rindex('f'))

try/except

Можно без явного if:

try:
    i = s.index('f')
except ValueError:  # count == 0
    pass
else:
    try:
        j = s.rindex('f', i+1)
    except ValueError:  # count == 1
        print(i)
    else:               # count > 1
        print(i, j)

Рекурсия

Можно рекурсивный find() реализовать:

def find(char, s, i=0):
    return -1 if i == len(s) else i if char == s[i] else find(char, s, i+1)

Тогда решение почти идентично варианту из вопроса(разница в том, что ничего не выводится для count==0 случая):

s = input()
i = find('f', s)
j = len(s) - 1 - find('f', s[::-1])  # rfind('f', s)
if i == -1:   # count == 0
    pass
elif i == j:  # count == 1
    print(i)
else:         # count > 1
    print(i, j)

Итераторы

Можно find() даже без индексации и явного len(s) реализовать:

def find(char, s, i=0):
    it = iter(s)
    first = next(it, None)
    return -1 if first is None else i if first == char else find(char, it, i+1)

Распаковка аргументов

Можно вообще не вызывать явно встроенные функции, опираясь на распаковку аргументов:

def find(char, s):
    def f(first, *rest, i=0):
        return i if first == char else -1 if not rest else f(*rest, i=i+1)
    return -1 if not s else f(*s)

Связные списки

Используя это представление, можно со строками как со связными списками работать. К примеру, чтобы обратить строку, получив связный список:

def reversed_as_llist(s):
    def f(first, *rest, llist=None):
        return f(*rest, llist=(first, llist)) if rest else (first, llist)
    return f(*s) if s else None

Пример:

>>> reversed_as_llist('abc')
('c', ('b', ('a', None)))

Используя явные функции доступа:

first = lambda llist: llist[0] if llist else None
rest = lambda llist: llist[1] if llist else None

легко найти размер списка, реализовать поиск по аналогии с приведёнными решениями:

def llist_len(llist, size=0):
    return llist_len(rest(llist), size+1) if llist else size

def llist_find(char, llist, i=0):
    return -1 if not llist else i if char == first(llist) else llist_find(char, rest(llist), i+1)

Это позволяет определить rfind() без len(s) и индексации (s[::-1]):

def rfind(char, s):
    L = reversed_as_llist(s)
    i = llist_find(char, L)
    return i if i == -1 else llist_len(L) - 1 - i

При желании, можно отказаться и от рекурсии с именованными функциями (к примеру, используя Y combinator) и даже не использовать явно числа (к примеру, заменяя на Church numerals).

heapq.nlargest

Если использовать встроенные функции, стандартную библиотеку, то есть множество решений, которые скрывают явный цикл и позволяют без .count('f') обойтись:

import heapq

indices = heapq.nlargest(2, range(len(s)), key=lambda i: s[i] == 'f')
fs = ''.join(map(s.__getitem__, indices))
if fs == 'ff':        # count == 2+
    print(*indices)
elif fs[:1] == 'f':   # count == 1
    print(indices[0])
# else print nothing  # count == 0

Обзор PHP-функций для работы со строками и практическое их применение с учетом кодировки UTF-8.

1

Количество символов

Получить длину строки

Функция strlen($string) возвращает длину строки, но возвращает неправильный результат если в строке есть кириллица в UTF-8, поэтому нужно использовать mb_strlen().

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';

echo strlen($text); // 105
echo mb_strlen($text); // 59

PHP

Количество символов без пробелов

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$str = mb_ereg_replace('[s]', '', $text);
echo mb_strlen($str); // 49

PHP

Количество слов с строке

Функция str_word_count() возвращает количество слов в строке, но символы обрамленные пробелами будет считаться за слово, например « — ». Так же функция не работает с UTF-8, как видно в примере:

$text = 'Lorem Ipsum - is simply dummy!';
echo str_word_count($text); // 6

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo str_word_count($text); // 1

PHP

Рабочий вариант:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$str = preg_replace("/[[:punct:]]/", '', $text);
$str = mb_ereg_replace('[s]+', ' ', $str);
$words = explode(' ', $str);
echo count($words); // 10

PHP

Получить количество переносов в строке

$text = 'Съешь ещё - этих 
мягких французских булок, 
да выпей же чаю.';

echo substr_count($text, PHP_EOL); // 2

PHP

Количество букв в строке

$text = 'Съешь ещё этих мягких французских булок, да выпей же чаю.';
echo $str = preg_replace('/[^a-zа-яё]/ui', '', $text);
echo mb_strlen($str); // 46

PHP

Количество цифр в строке

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$str = preg_replace('/[^0-9]/ui', '', $text);
echo mb_strlen($str); // 0

PHP

Количество знаков препинания

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$str = preg_replace("/[^[:punct:]]/", '', $text);
echo mb_strlen($str); // 3

PHP

Количество пробелов в строке

Или количество вхождений любого другого символа или подстроки.

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo substr_count($text, ' '); // 10

PHP

Количество пробелов в начале строки:

$text = '     Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo mb_strlen($text) - mb_strlen(ltrim($text, ' ')); // 5

PHP

Количество пробелов в конце строки:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.   ';
echo mb_strlen($text) - mb_strlen(rtrim($text, ' ')); // 3

PHP

2

Поиск

Получить количество вхождений подстроки

$text = 'Съешь ещё - этих мягких французских булок, да ещё выпей же чаю.';
echo mb_substr_count($text, 'ещё'); // 2

PHP

Найти позицию первого вхождения подстроки

$text = 'Съешь ещё - этих мягких французских булок, да ещё выпей же чаю.';
echo mb_strpos($text, 'ещё'); // 6

// Без учета регистра:
$text = 'Съешь ещё - этих мягких французских булок, да ещё выпей же чаю.';
echo mb_stripos($text, 'ещё'); // 6

PHP

Найти позицию последнего вхождения подстроки

$text = 'Съешь ещё - этих мягких французских булок, да ещё выпей же чаю.';
echo mb_strrpos($text, 'ещё'); // 46

// Без учета регистра:
$text = 'Съешь ещё - этих мягких французских булок, да ещё выпей же чаю.';
echo mb_strirpos($text, 'ещё'); // 46

PHP

Найти все вхождения подстроки

$text = 'Съешь ещё - этих мягких французских булок, да ещё выпей же чаю.';

$offset = 0;
$allpos = array();
while (($pos = mb_strpos($text, 'ещё', $offset)) !== false) {
	$offset   = $pos + 1;
	$allpos[] = $pos;
}

print_r($allpos); // Array ([0] => 6 [1] => 46)

PHP

3

Извлечение из текста

Начало строки

Получить первый символ:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo mb_substr($text, 0, 1); // С

PHP

Получить три первых символа:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo mb_substr($text, 0, 3); // Съе

PHP

Получить первое слово:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo mb_strstr($text, ' ', true); // Съешь

PHP

Получить все после первого слова:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo mb_strstr($text, ' ', false); // ещё - этих мягких французских булок, да выпей же чаю.

PHP

Конец строки

Получить последний символ:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo mb_substr($text, -1, 1); // .

PHP

Получить три последних символа:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo mb_substr($text, -1, 3); // аю.

PHP

Получить последнее слово:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$array = explode(' ', $text);
echo end($array); // чаю.

PHP

Получить всё до последнего слова:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$str = mb_substr($text, 0, mb_strrpos($text, ' '));
echo $str; // Съешь ещё - этих мягких французских булок, да выпей же

PHP

Середина строки

Получить второе слово:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$array = explode(' ', $text);
echo $array[1]; // ещё

PHP

Получить текст до дефиса:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo mb_substr($text, 0, mb_strpos($text, ' - ')); // Съешь ещё

PHP

Получить текст после дефиса:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$str = mb_substr($text, mb_strpos($text, ' - ') + mb_strlen(' - '), -1);
echo $str; // этих мягких французских булок, да выпей же чаю

PHP

Переносы строк

Получить первую строку:

$text = 'Разнообразный опыт укрепление и развитие структуры требуют 
определения направлений прогрессивного развития! Не следует забывать, 
что постоянный рост и сфера активности в  степени обуславливает создание 
системы обучения кадров? С другой стороны дальнейшее развитие различных 
форм влечет за собой процесс внедрения и модернизации.';

$pos = mb_strpos($text, "n");
$str = trim(mb_substr($text, 0, $pos));
echo $str; // Разнообразный опыт укрепление и развитие структуры требуют 

// или
$lines = explode("n", $text);
echo $lines[0]; // Разнообразный опыт укрепление и развитие структуры требуют 

PHP

Получить последнюю строку:

$text = 'Разнообразный опыт укрепление и развитие структуры требуют 
определения направлений прогрессивного развития! Не следует забывать, 
что постоянный рост и сфера активности в  степени обуславливает создание 
системы обучения кадров? С другой стороны дальнейшее развитие различных 
форм влечет за собой процесс внедрения и модернизации.';

$pos = mb_strrpos($text, "n");
$str = trim(mb_substr($text, $pos));
echo $str; // форм влечет за собой процесс внедрения и модернизации.

// или
$lines = explode("n", $text);
echo end($lines); // форм влечет за собой процесс внедрения и модернизации.

PHP

Пилучить символы из ковычек и скобок

$text = ''Съешь' "ещё" «этих» [мягких] (французских) {булок} <да>';

// '...'
preg_match_all("/'(.+?)'/", $text, $matches);
echo $matches[1][0]; // Съешь

// "..."
preg_match_all("/"(.+?)"/", $text, $matches);
echo $matches[1][0]; // ещё

// «...»
preg_match_all("/«(.+?)»/", $text, $matches);
echo $matches[1][0]; // этих

// [...]
preg_match_all("/[(.+?)]/", $text, $matches);
echo $matches[1][0]; // мягких

// (...)
preg_match_all("/((.+?))/", $text, $matches);
echo $matches[1][0]; // французских

// {...}
preg_match_all("/{(.+?)}/", $text, $matches);
echo $matches[1][0]; // булок

// <...>
preg_match_all("/<(.+?)>/", $text, $matches);
echo $matches[1][0]; // да

PHP

4

Замена в строках

Функция substr_replace($search, $replace, $subject, $count) – заменяет часть строки, также не раотает с кирилицей в кодировке UTF-8, в библиатеке mb_string её нет, поэтому приходится использовать пользовольскую функцию:

if (!function_exists('mb_substr_replace')) {
	function mb_substr_replace($original, $replacement, $position, $length)
	{
		$startString = mb_substr($original, 0, $position, 'UTF-8');
		$endString = mb_substr($original, $position + $length, mb_strlen($original), 'UTF-8');
		$out = $startString . $replacement . $endString;
		return $out;
	}
}

PHP

Заменить первый символ:

$text = 'Съешь ещё - этих мягких французских булок.';
echo mb_substr_replace($text, '!', 0, 1); // !ъешь ещё - этих мягких французских булок.

PHP

Заменить три первых символа:

$text = 'Съешь ещё - этих мягких французских булок.';
echo mb_substr_replace($text, '!!!', 0, 3); // !!!шь ещё - этих мягких французских булок.

PHP

Заменить последний символ:

$text = 'Съешь ещё - этих мягких французских булок.';
echo mb_substr_replace($text, '!', -1, 0); // Съешь ещё - этих мягких французских булок!

PHP

Заменить три последних символа:

$text = 'Съешь ещё - этих мягких французских булок.';
echo mb_substr_replace($text, '!!!', -3, 0); // Съешь ещё - этих мягких французских бул!!!

PHP

Замена символов и слов в строке

Для этой задачи подходит функция str_replace($search, $replace, $subject), которая работает со всеми кодировками.

Заменить пробелы:

$text = 'Съешь ещё - этих мягких французских булок.';
echo str_replace(' ', '-', $text); // Съешь-ещё---этих-мягких-французских-булок.

PHP

Заменить слово:

$text = 'Съешь ещё - этих мягких французских булок.';
echo str_replace('мягких', 'твердых', $text); // Съешь ещё - этих твердых французских булок.

PHP

Заменить всё до дефиса:

$text = 'Съешь ещё - этих мягких французских булок.';

$str = 'Не ешь' . mb_substr($text, mb_strpos($text, ' - '), -1);
echo $str; // Не ешь - этих мягких французских булок

PHP

Заменить всё после дефиса:

$text = 'Съешь ещё - этих мягких французских булок.';

$str = mb_substr($text, 0, mb_strpos($text, ' - ') + 3) . 'печенек';
echo $str; // Съешь ещё - печенек

PHP

5

Добавление в строки

Добавить строку после 10-го символа:

$text = 'Съешь ещё - этих мягких французских булок.';

$str = mb_substr_replace($text, '!!!', 10, 0);
echo $str; // Съешь ещё !!!- этих мягких французских булок.

PHP

Добавить перед словом:

$text = 'Съешь ещё - этих мягких французских булок.';

$str = str_replace(' ещё ', ' же ещё ', $text); 
echo $str; // Съешь же ещё - этих мягких французских булок.

PHP

Добавить после слова:

$text = 'Съешь ещё - этих мягких французских булок.';
$str = str_replace(' ещё ', ' ещё немного ', $text); 
echo $str; // Съешь ещё немного - этих мягких французских булок.

PHP

Вставить строку между всех символов

Для того чтобы вставить символ между всех символов в строке понадобится функция str_split($string) для пробразавания строки в массив, она также не работает с кирилицей. С версии PHP 7.4 появилась функция mb_str_split(), для более ранних версий:

if (!function_exists('mb_str_split')) {
	function mb_str_split($str, $l = 0) {
		if ($l > 0) {
			$ret = array();
			$len = mb_strlen($str, "UTF-8");
			for ($i = 0; $i < $len; $i += $l) {
				$ret[] = mb_substr($str, $i, $l, "UTF-8");
			}
			return $ret;
		}
		return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
	}
}

PHP

$text = 'Съешь ещё - этих мягких французских булок.';

$array = mb_str_split($text);;
$new = implode(' ', $array);
echo $new; // С ъ е ш ь   е щ ё   -   э т и х   м я г к и х   ф р а н ц у з с к и х   б у л о к .

PHP

Дописать строку до нужной длины

Функция str_pad($string, $length, $pad_string, $pad_type) дополняет строку другой строкой до заданной длины.

Версия функции для UTF-8:

if (!function_exists('mb_str_pad')) {
	function mb_str_pad($input, $pad_length, $pad_string = ' ', $pad_type = STR_PAD_RIGHT)
	{
		$diff = strlen($input) - mb_strlen($input);
		return str_pad($input, $pad_length + $diff, $pad_string, $pad_type);
	}
}

PHP

Дописать стркуку слева:

$text = 'Привет Мир';
echo mb_str_pad($text,  20, '-', STR_PAD_LEFT); // ----------Привет Мир

PHP

Дописать строку справа:

$text = 'Привет Мир';
echo mb_str_pad($text,  20, '-', STR_PAD_RIGHT); // Привет Мир----------

PHP

Дописать строку с обеих сторон:

$text = 'Привет Мир';
echo mb_str_pad($text,  20, '-', STR_PAD_BOTH); // -----Привет Мир-----

PHP

6

Удаление из строк

Удаление в начале строки

Удалить первый символ:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = mb_substr($text, 1);
echo $new; // ъешь ещё - этих мягких французских булок, да выпей же чаю.

PHP

Удалить первые 3 символа:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = mb_substr($text, 3);
echo $new; // шь ещё - этих мягких французских булок, да выпей же чаю.

PHP

Удалить первое слово:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = mb_substr($text, mb_strpos($text, ' '));
echo $new; // ещё - этих мягких французских булок, да выпей же чаю.

PHP

Удаление в конце строки

Удалить последний символ:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = mb_substr($text, 0, -1);
echo $new; // Съешь ещё - этих мягких французских булок, да выпей же чаю

PHP

Удалить три последних символа:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = mb_substr($text, 0, -3);
echo $new; // Съешь ещё - этих мягких французских булок, да выпей же ч

PHP

Удалить последнее слово:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = mb_substr($text, 0, mb_strrpos($text, ' '));
echo $new; // Съешь ещё - этих мягких французских булок, да выпей же

PHP

Удаление подсторк

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = str_replace(' мягких', '', $text);
echo $new; // Съешь ещё - этих французских булок, да выпей же чаю.

PHP

Удалить всё перед сиволом:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = strstr($text, '-'); 
echo $new; // - этих мягких французских булок, да выпей же чаю.

PHP

Удалить всё после сивола:

$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = strstr($text, '-', true); 
echo $new; // Съешь ещё

// Второй вариант:
$pos = mb_strpos($text, '-');
$new = mb_substr($text, 0, $pos + 1);
echo $new; // Съешь ещё -

PHP

strrchr

(PHP 4, PHP 5, PHP 7)

strrchrНаходит последнее вхождение символа в строке

Описание

string strrchr
( string $haystack
, mixed $needle
)

Список параметров

haystack

Строка, в которой производится поиск

needle

Если needle состоит более чем из
одного символа, используется только первый символ. Это поведение
отличается от strstr().

Если needle не является строкой, он приводится
к целому и трактуется как код символа.

Возвращаемые значения

Функция возвращает фрагмент строки, или FALSE, если подстрока
needle не найдена.

Список изменений

Версия Описание
4.3.0 Эта функция теперь бинарно-безопасна.

Примеры

Пример #1 Пример использования strrchr()


<?php
// получить последнюю директорию из $PATH
$dir substr(strrchr($PATH":"), 1);// получить все после последнего перевода строки
$text "Line 1nLine 2nLine 3";
$last substr(strrchr($text10), );
?>

Примечания

Замечание: Эта функция безопасна
для обработки данных в двоичной форме.

Смотрите также

  • strstr() — Находит первое вхождение подстроки
  • strrpos() — Возвращает позицию последнего вхождения подстроки в строке

Вернуться к: Обработка строк

Понравилась статья? Поделить с друзьями:
  • Как в ворде найти отдельное слово
  • Как найти компанию для охоты
  • Как найти файл который устанавливает программы
  • Как найти молодого человека за неделю
  • Как найти утечку в электрике авто