php удалить подстроку в строке
Функция str_replace в php нужна для замены подстроки в строке.
У функции следующие параметры:
Замена подстроки
Пример: заменим bbb на zzz:
А что если нам нужно также заменить и ccc на zzz? Мы бы конечно могли запустить функцию 2 раза, в первый раз заменив первую подстроку, а второй раз другую, но можно просто указать массив подстрок поиска первым параметром.
Пример: заменим bbb и ccc на zzz:
Что если нам нужно заменить bbb на zzz, а ccc на www?
Мы конечно снова можем запустить функцию 2 раза, но оптимальнее с точки зрения производительности будет и вторым параметром передать массив. В первом массиве будут подстроки, которые мы ищем, а во втором те, на которые заменяем.
Пример: заменяем bbb на zzz, а ccc на www:
Результат у нас правильный, но читабельность конечно страдает. А представьте если бы мы указывали сразу 50 таких строк для замены? И потом когда мы добавляем или заменяем строку, ее приходилось бы искать в 2 местах.
Более читабельным был бы код:
Тут нам помогли функции array_keys и array_values которые вернули все ключи и все значения соответственно. Кстати для подобной замены вам не обязательно использовать функцию str_replace, а можно воспользоваться strtr, и тогда наш код выглядел бы еще более просто:
Таким образом если дополнить наш пример:
Удаление подстроки
Хоть это и очевидно, давайте проговорим еще момент с удалением строк. Чтобы удалить подстроку нужно просто заменить ее на пустоту (пустую строку).
Удалим xx из нашей строки:
Другие примеры
Рассмотрим еще несколько примеров:
Эта функция не поддерживает регулярные выражения, но для этого есть другая функция: preg_replace()
Более мощная альтернатива: preg_replace
С помощью функции preg_replace вы можете осуществлять замену по регулярном выражению. Если вам не хватает возможностей str_replace, то обратите внимание на эту функцию.
Продвинутая работа со строками
Если вы часто работаете со строками, то возможно вам пригодятся более высокоуровневые методы для их обработки.
Взгляните как будут выглядеть поиск и замена строк с помощью symfony/string:
Как видите здесь есть много полезных методов, для написания которых мы с вами могли бы потратить много времени. Посмотрите также другие полезные примеры работы с symfony/string
Как с помощью PHP удалить символ – все способы реализации
Дата публикации: 2017-05-19
От автора: может, слов не выкинешь из песни. Но вот в PHP удалить символ проще простого. Сегодня этим и займемся.
Функциональный подход
Имеется в виду использование встроенных в ядро языка функций. Сначала используем str_replace(). Она принимает три аргумента: символ замены, заменяемый символ и исходную строку. Пример:
Бесплатный курс по PHP программированию
Освойте курс и узнайте, как создать динамичный сайт на PHP и MySQL с полного нуля, используя модель MVC
В курсе 39 уроков | 15 часов видео | исходники для каждого урока
Но это не единственная функция для изъятия «нежелательного» элемента из строки. Вот еще одна:
Здесь для удаления определенных частей текста применяем функцию substr(). В качестве параметров передаем ей первоначальную строку, положение, с которого нужно отсечь строку, и положение последнего знака возвращаемой подстроки.
Использование данной функции оправдано, если знаете очередность символа, который нужно изъять.
Вот еще одна функция, помогающая в решении проблемы. strstr() возвращает часть строки до или после переданного ей символа. Как от него избавиться:
Для этого в параметрах функции указываем true и получаем левую часть строки от символа, но уже без него.
Регулярки, потому что регулярно
Как всегда, господа, «на второе» у нас регулярные выражения. Их использование крайне удобно для решения некоторых «неудобных» ситуаций. К примеру, если нужно избавиться от повторяющихся знаков:
Здесь применяется функция для работы с регулярками preg_replace(). В переданной ей строке она ищет заданный символ и меняет его на другой. В приведенном выше примере таким образом мы избавились от нулей в тексте.
Бесплатный курс по PHP программированию
Освойте курс и узнайте, как создать динамичный сайт на PHP и MySQL с полного нуля, используя модель MVC
В курсе 39 уроков | 15 часов видео | исходники для каждого урока
Разработка веб-приложения на PHP
Создайте веб-приложение на PHP на примере приема платежей на сайте
substr_replace
(PHP 4, PHP 5, PHP 7, PHP 8)
substr_replace — Заменяет часть строки
Описание
Список параметров
Возвращаемые значения
Возвращает результирующую строку. Если string является массивом, то возвращает массив.
Список изменений
Версия | Описание |
---|---|
8.0.0 | length теперь допускает значение null. |
Примеры
Пример #1 Простой пример использования substr_replace()
Пример #2 Использование substr_replace() для одновременной множественной замены строк
Результат выполнения данного примера:
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Смотрите также
User Contributed Notes 35 notes
Forget all of the mb_substr_replace() implementations mentioned in this page, they’re all buggy.
Here is a version that mimics the behavior of substr_replace() exactly:
PHP version of Java’s removeCharAt() function:
Using substr_replace() can be avoided by using substr() instead:
This can be useful when you need to replace parts of multibyte strings like strings encoded with utf-8. There isn’t a multibute variant for substr_replace(), but for php substr() there is mb_substr(). For more information on multibyte strings see http://nl3.php.net/manual/en/ref.mbstring.php
I’ve just taken a look at the post by ntoniazzi and I have a very small correction to make.
In the second if statement, it should be a triple equals, so:
I wrote a function that you can use for example in combination with a search script to cut off the articles that are too long.
I recently ran across a situation where I need to strip a heavily nested html list such that only the top level was preserved. I started with a regular expression solution, but found that I kept matching the wrong closing ul with an outer opening ul.
This was my alternative solution, and it seems to work well:
?>
Hope this helps someone.
This will truncate a longer string to a smaller string of specified length while replacing the middle portion with a separator exactly in the middle.
//prints «abcdefghij/. /56789z.jpg»
I have a little function that works like substr_replace () what I use for some purpose. Maybe someone needs it.
This is a small powerful function that performs its job flawlessly.
I suggest changing the function suggested by Guru Evi slightly. I found that it doesn’t work as written here.
If your string is not long enough to meet what you specify in start and length then the replacement string is added towards the end of the string.
I use strip_tags to strip out the HTML otherwise you might get a screwed up HTML (when a tags open in the string, but because you cut-off it doesn’t)
THE DOT DOT DOT ISSUE
PROBLEM:
You want to abbreviate a string.
E.g. You want «BritneySpears» to show as «BritneySpe. «, being only the ten first characters followed by «. «
This will result in BritneySpe.
The older function would end up looking like «blah blah. » or «blah blah. » which doesn’t look so nice to me.
$punctuation = «. ;,-» ; //punctuation you want removed
Here is a simple function to shorten a string and add an ellipsis
This may be obvious to others, but I just spent hours and my feeble brain only caught up to it after a long break.
If you are looping through a string which has multiple substrings that need to be replaced, you have to add an offset factor to each original offset before you replaced any strings. Here is a real world example:
From draft.js we get paragraphs with multiple links designated only with offset, anchor text length, url, target. So each anchor text must be wrapped in the anchortext to save proper content in the database.
Here is the implementation of offset factor:
I hope this helps a noobie 🙂 If there is another easier way, I would love to hear about it.
First Example can be simplified =>
$input = array(‘A: XXX’, ‘B: XXX’, ‘C: XXX’);
output: Array ( [0] => A: YYY [1] => B: YYY [2] => C: YYY )
I recently needed a routine that would remove the characters in one string from another, like the regex
I don’t know if this function is multibyte safe but I’ve written a function that will do the same in multibyte mode.
Just to add to the examples, if replacement is longer than length, only the length number of chars are removed from string and all of replacement is put in its place, and therefor strlen($string) is inreased.
$var = ‘ABCDEFGH:/MNRPQR/’;
/* Should return ABCDEFGH:/testingRPQR/ */
echo substr_replace ($var, ‘testing’, 10, 2);
If you would like to remove characters from the start or end of a string, try the substr() function.
The comment by geniusdex is a good one. Short, simple functions are the best. But if the string is not longer than the limit set, NOTHING is returned. Here is the function re-done to always return a string:
Regarding «. «, even the short functions are too long and complicated, and there’s no need to use substr_replace. substr() works better and is way faster prior to 4.3.5 as the below poster stated.
This is my version of making dotted strings:
To abbreviate links into ‘. ‘ if they outreach a certain amount of space; use the preg_replace function instead.
For instance you grabbed the headlines of a news site for use on your own page and the lines are to long:
Функции для работы со строками
Для получения информации о более сложной обработке строк обратитесь к функциями Perl-совместимых регулярных выражений. Для работы с многобайтовыми кодировками посмотрите на функции по работе с многобайтовыми кодировками.
Содержание
User Contributed Notes 24 notes
In response to hackajar yahoo
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.
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)
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. 🙂
Just a note in regards to bloopletech a few posts down:
The word «and» should not be used when converting numbers to text. «And» (at least in US English) should only be used to indicate the decimal place.
Example:
1,796,706 => one million, seven hundred ninety-six thousand, seven hundred six.
594,359.34 => five hundred ninety four thousand, three hundred fifty nine and thirty four hundredths
/*
* example
* accept only alphanum caracteres from the GET/POST parameters ‘a’
*/
to: james dot d dot baker at gmail dot com
PHP has a builtin function for doing what your function does,
/**
Utility class: static methods for cleaning & escaping untrusted (i.e.
user-supplied) strings.
Any string can (usually) be thought of as being in one of these ‘modes’:
pure = what the user actually typed / what you want to see on the page /
what is actually stored in the DB
gpc = incoming GET, POST or COOKIE data
sql = escaped for passing safely to RDBMS via SQL (also, data from DB
queries and file reads if you have magic_quotes_runtime on—which
is rare)
html = safe for html display (htmlentities applied)
Always knowing what mode your string is in—using these methods to
convert between modes—will prevent SQL injection and cross-site scripting.
This class refers to its own namespace (so it can work in PHP 4—there is no
self keyword until PHP 5). Do not change the name of the class w/o changing
all the internal references.
Example usage: a POST value that you want to query with:
$username = Str::gpc2sql($_POST[‘username’]);
*/
Example: Give me everything up to the fourth occurance of ‘/’.
//
// 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.
//
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.
?>
Example: Give me everything up to the fourth occurance of ‘/’.
The functions below:
Are correct, but flawed. You’d need to use the === operator instead:
Here’s an easier way to find nth.
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 http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_substring#PHP so here I post you the function
Here’s a simpler «simplest» way to toggle through a set of 1..n colors for web backgrounds:
If you want a function to return all text in a string up to the Nth occurrence of a substring, try the below function.
(Pommef provided another sample function for this purpose below, but I believe it is incorrect.)
/*
// prints:
S: d24jkdslgjldk2424jgklsjg24jskgldjk24
1: d
2: d24jkdslgjldk
3: d24jkdslgjldk24
4: d24jkdslgjldk2424jgklsjg
5: d24jkdslgjldk2424jgklsjg24jskgldjk
6: d24jkdslgjldk2424jgklsjg24jskgldjk24
7: d24jkdslgjldk2424jgklsjg24jskgldjk24
*/
?>
Note that this function can be combined with wordwrap() to accomplish a routine but fairly difficult web design goal, namely, limiting inline HTML text to a certain number of lines. wordwrap() can break your string using
, and then you can use this function to only return text up to the N’th
.
You will still have to make a conservative guess of the max number of characters per line with wordwrap(), but you can be more precise than if you were simply truncating a multiple-line string with substr().
= ‘Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida accumsan, enim quam condimentum est, vitae rutrum neque magna ac enim.’ ;
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu
dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida
str_replace()
Синтаксис:
str_replace(search, replace, subject[, count])
Поддерживается следующими версиями PHP:
Описание функции:
Функции str_replace() производит замену одних символов в строке другими.
Обязательный аргумент. Строка или массив поиска
Использование функции str_replace() предпочтительнее использованию функции preg_replace(), так как работает быстрее.
Функция str_replace() отличается от функции str_ireplace() тем, что чувствительна к регистру.
Примеры:
Пример 1:
echo str_replace(«Вова»,»Дима»,»С добрым утром Вова!»);
?>
С добрым утром Дима!
Пример 2:
В этом примере показано использование массивов
$arr1 = array(«1″,»2″,»3»);
$arr2 = array(«a»,»b»,»c»);
echo str_replace($arr2,$arr1,»cabdfg»);
?>
Пример 3:
В этом примере показано использование массивов во всех аргументах
$arr1 = array(«1″,»2″,»3»);
$arr2 = array(«a»,»b»,»c»);
$arr3 = array(«t»,»c»,»a»);
print_r (str_replace($arr2,$arr1,$arr3));
?>