Замена символа в строке PHP
Часто бывает необходимо заменить точку на запятую или наоборот, чтобы исключить возникающие ошибки, например перед сохранением в базу. Сделать это достаточно просто, при помощи функции str_replace , куда первым параметром передается символ, который нужно заменить, а вторым на что заменить. Ниже примеры кода и результат выполнения.
Пример 1, замена точки на запятую:
$varToReplace = '25.00'; $varToReplace = str_replace('.', ',', $varToReplace); echo $varToReplace;
В результате мы получим: 25,00
Пример 2, замена пробела на тире:
$varToReplace = 'Добрый день слово 1'; $varToReplace = str_replace(' ','-',$varToReplace); echo $varToReplace;
В результате мы получим: Добрый-день-слово-1
В принципе, при помощи данной функции можно и удалить символы из строки, например уберем все буквы «а» из строки «Здравствуйте, как у Вас дела?»
Пример 3, удаление символов в строке:
$varToReplace = 'Здравствуйте, как у Вас дела?'; $varToReplace = str_replace('а','',$varToReplace); echo $varToReplace;
В результате получим «Здрвствуйте, кк у Вс дел?» . Для этого просто передаем во втором параметре отсутствие символа, то есть кавычки без символов и пробелов.
str_replace
Эта функция возвращает строку или массив, в котором все вхождения search в subject заменены на replace .
Чтобы заменить текст на основе шаблона, а не фиксированной строки, используйте функцию preg_replace() .
Список параметров
Если search и replace — массивы, то str_replace() использует каждое значение из соответствующего массива для поиска и замены в subject . Если в массиве replace меньше элементов, чем в search , в качестве строки замены для оставшихся значений будет использована пустая строка. Если search — массив, а replace — строка, то эта строка замены будет использована для каждого элемента массива search . Обратный случай смысла не имеет.
Если search или replace являются массивами, их элементы будут обработаны от первого к последнему.
Искомое значение, также известное как needle (иголка). Для множества искомых значений можно использовать массив.
Значение замены, будет использовано для замены искомых значений search . Для множества значений можно использовать массив.
Строка или массив, в котором производится поиск и замена, также известный как haystack (стог сена).
Если subject является массивом, то поиск с заменой будет осуществляться над каждым элементом subject , а результатом функции также будет являться массив.
Если передан, то будет установлен в количество произведённых замен.
Возвращаемые значения
Эта функция возвращает строку или массив с заменёнными значениями.
Примеры
Пример #1 Примеры использования str_replace()
// присваивает: Hll Wrld f PHP
$vowels = array( «a» , «e» , «i» , «o» , «u» , «A» , «E» , «I» , «O» , «U» );
$onlyconsonants = str_replace ( $vowels , «» , «Hello World of PHP» );
// присваивает: You should eat pizza, beer, and ice cream every day
$phrase = «You should eat fruits, vegetables, and fiber every day.» ;
$healthy = array( «fruits» , «vegetables» , «fiber» );
$yummy = array( «pizza» , «beer» , «ice cream» );
$newphrase = str_replace ( $healthy , $yummy , $phrase );
// присваивает: 2
$str = str_replace ( «ll» , «» , «good golly miss molly!» , $count );
echo $count ;
?>
Пример #2 Примеры потенциальных трюков с str_replace()
// Порядок замены
$str = «Строка 1\nСтрока 2\rСтрока 3\r\nСтрока 4\n» ;
$order = array( «\r\n» , «\n» , «\r» );
$replace = ‘
‘ ;
?php
// Обрабатывает сначала \r\n для избежания их повторной замены.
echo $newstr = str_replace ( $order , $replace , $str );
// Выводит F, т.к. A заменяется на B, затем B на C, и так далее.
// В итоге E будет заменено F, так как замена происходит слева направо.
$search = array( ‘A’ , ‘B’ , ‘C’ , ‘D’ , ‘E’ );
$replace = array( ‘B’ , ‘C’ , ‘D’ , ‘E’ , ‘F’ );
$subject = ‘A’ ;
echo str_replace ( $search , $replace , $subject );
// Выводит: яблорехкорех орех (по вышеуказанной причине)
$letters = array( ‘я’ , ‘о’ );
$fruit = array( ‘яблоко’ , ‘орех’ );
$text = ‘я о’ ;
$output = str_replace ( $letters , $fruit , $text );
echo $output ;
?>
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Предостережение
Замечание о порядке замены
Так как str_replace() осуществляет замену слева направо, то при использовании множественных замен она может заменить ранее вставленное значение на другое. Смотрите также примеры на этой странице.
Замечание:
Эта функция чувствительна к регистру. Используйте str_ireplace() для замены без учёта регистра.
Смотрите также
- str_ireplace() — Регистронезависимый вариант функции str_replace
- substr_replace() — Заменяет часть строки
- preg_replace() — Выполняет поиск и замену по регулярному выражению
- strtr() — Преобразовывает заданные символы или заменяет подстроки
User Contributed Notes 34 notes
13 years ago
A faster way to replace the strings in multidimensional array is to json_encode() it, do the str_replace() and then json_decode() it, like this:
function str_replace_json ( $search , $replace , $subject ) <
return json_decode ( str_replace ( $search , $replace , json_encode ( $subject )));
>
?>
This method is almost 3x faster (in 10000 runs.) than using recursive calling and looping method, and 10x simpler in coding.
function str_replace_deep ( $search , $replace , $subject )
<
if ( is_array ( $subject ))
<
foreach( $subject as & $oneSubject )
$oneSubject = str_replace_deep ( $search , $replace , $oneSubject );
unset( $oneSubject );
return $subject ;
> else <
return str_replace ( $search , $replace , $subject );
>
>
?>
12 years ago
Note that this does not replace strings that become part of replacement strings. This may be a problem when you want to remove multiple instances of the same repetative pattern, several times in a row.
If you want to remove all dashes but one from the string ‘-aaa—-b-c——d—e—f’ resulting in ‘-aaa-b-c-d-e-f’, you cannot use str_replace. Instead, use preg_replace:
$challenge = ‘-aaa—-b-c——d—e—f’ ;
echo str_replace ( ‘—‘ , ‘-‘ , $challenge ). ‘
‘ ;
echo preg_replace ( ‘/—+/’ , ‘-‘ , $challenge ). ‘
‘ ;
?>
This outputs the following:
-aaa—b-c—d-e—f
-aaa-b-c-d-e-f
14 years ago
Be careful when replacing characters (or repeated patterns in the FROM and TO arrays):
$arrFrom = array( «1» , «2» , «3» , «B» );
$arrTo = array( «A» , «B» , «C» , «D» );
$word = «ZBB2» ;
echo str_replace ( $arrFrom , $arrTo , $word );
?>
I would expect as result: «ZDDB»
However, this return: «ZDDD»
(Because B = D according to our array)
To make this work, use «strtr» instead:
$arr = array( «1» => «A» , «2» => «B» , «3» => «C» , «B» => «D» );
$word = «ZBB2» ;
echo strtr ( $word , $arr );
?>
This returns: «ZDDB»
14 years ago
Feel free to optimize this using the while/for or anything else, but this is a bit of code that allows you to replace strings found in an associative array.
For example:
$replace = array(
‘dog’ => ‘cat’ ,
‘apple’ => ‘orange’
‘chevy’ => ‘ford’
);
$string = ‘I like to eat an apple with my dog in my chevy’ ;
echo str_replace_assoc ( $replace , $string );
// Echo: I like to eat an orange with my cat in my ford
?>
Here is the function:
function strReplaceAssoc (array $replace , $subject ) <
return str_replace ( array_keys ( $replace ), array_values ( $replace ), $subject );
>
?>
[Jun 1st, 2010 — EDIT BY thiago AT php DOT net: Function has been replaced with an updated version sent by ljelinek AT gmail DOT com]
14 years ago
As previous commentators mentioned, when $search contains values that occur earlier in $replace, str_replace will factor those previous replacements into the process rather than operating solely on the original string. This may produce unexpected output.
$search = array( ‘A’ , ‘B’ , ‘C’ , ‘D’ , ‘E’ );
$replace = array( ‘B’ , ‘C’ , ‘D’ , ‘E’ , ‘F’ );
$subject = ‘ABCDE’ ;
echo str_replace ( $search , $replace , $subject ); // output: ‘FFFFFF’
?>
In the above code, the $search and $replace should replace each occurrence in the $subject with the next letter in the alphabet. The expected output for this sample is ‘BCDEF’; however, the actual output is ‘FFFFF’.
To more clearly illustrate this, consider the following example:
$search = array( ‘A’ , ‘B’ , ‘C’ , ‘D’ , ‘E’ );
$replace = array( ‘B’ , ‘C’ , ‘D’ , ‘E’ , ‘F’ );
$subject = ‘A’ ;
echo str_replace ( $search , $replace , $subject ); // output: ‘F’
?>
Since ‘A’ is the only letter in the $search array that appears in $subject, one would expect the result to be ‘B’; however, replacement number $n does *not* operate on $subject, it operates on $subject after the previous $n-1 replacements have been completed.
The following function utilizes array_combine and strtr to produce the expected output, and I believe it is the most efficient way to perform the desired string replacement without prior replacements affecting the final result.
/**
* When using str_replace(. ), values that did not exist in the original string (but were put there by previous
* replacements) will be replaced continuously. This string replacement function is designed replace the values
* in $search with those in $replace while not factoring in prior replacements. Note that this function will
* always look for the longest possible match first and then work its way down to individual characters.
*
* The «o» in «stro_replace» represents «original», indicating that the function operates only on the original string.
*
* @param array $search list of strings or characters that need to be replaced
* @param array $replace list of strings or characters that will replace the corresponding values in $search
* @param string $subject the string on which this operation is being performed
*
* @return string $subject with all substrings in the $search array replaced by the values in the $replace array
*/
function stro_replace ( $search , $replace , $subject )
return strtr ( $subject , array_combine ( $search , $replace ) );
>
$search = array( ‘A’ , ‘B’ , ‘C’ , ‘D’ , ‘E’ );
$replace = array( ‘B’ , ‘C’ , ‘D’ , ‘E’ , ‘F’ );
$subject = ‘ABCDE’ ;
echo stro_replace ( $search , $replace , $subject ); // output: ‘BCDEF’
?>
Some other examples:
// We want to replace the spaces with and the ampersand with &
echo str_replace ( $search , $replace , $subject ); // output: «Hello & goodbye!» — wrong!
echo stro_replace ( $search , $replace , $subject ); // output: «Hello & goodbye!» — correct!
/*
Note: Run the above code in the CLI or view source on your web browser — the replacement strings for stro_replace are HTML entities which the browser interprets.
*/
?>
$search = array( ‘ERICA’ , ‘AMERICA’ );
$replace = array( ‘JON’ , ‘PHP’ );
$subject = ‘MIKE AND ERICA LIKE AMERICA’ ;
// We want to replace the name «ERICA» with «JON» and the word «AMERICA» with «PHP»
echo str_replace ( $search , $replace , $subject ); // output: «MIKE AND JON LIKE AMJON», which is not correct
echo stro_replace ( $search , $replace , $subject ); // output: «MIKE AND JON LIKE PHP», which is correct
?>
17 years ago
As an effort to remove those Word copy and paste smart quotes, I’ve found that this works with UTF8 encoded strings (where $text in the following example is UTF8). Also the elipsis and em and en dashes are replaced.
There is an «invisible» character after the †for the right side double smart quote that doesn’t seem to display here. It is chr(157).
$find [] = ‘“’ ; // left side double smart quote
$find [] = ‘‒ ; // right side double smart quote
$find [] = ‘‘’ ; // left side single smart quote
$find [] = ‘’’ ; // right side single smart quote
$find [] = ‘…’ ; // elipsis
$find [] = ‘—’ ; // em dash
$find [] = ‘–’ ; // en dash
$replace [] = ‘»‘ ;
$replace [] = ‘»‘ ;
$replace [] = «‘» ;
$replace [] = «‘» ;
$replace [] = «. » ;
$replace [] = «-» ;
$replace [] = «-» ;
$text = str_replace ( $find , $replace , $text );
?>
7 years ago
Be aware that if you use this for filtering & sanitizing some form of user input, or remove ALL instances of a string, there’s another gotcha to watch out for:
// Remove all double characters
$string=»1001011010″;
$string=str_replace(array(«11″,»00″),»»,$string);
// Output: «110010»
$string=»ml> Malicious code html> etc»;
$string=str_replace(array(««,»«),»»,$string);
// Output: » Malicious code etc»
12 years ago
This strips out horrible MS word characters.
Just keep fine tuning it until you get what you need, you’ll see ive commented some out which caused problems for me.
There could be some that need adding in, but its a start to anyone who wishes to make their own custom function.
function msword_conversion ( $str )
<
$str = str_replace ( chr ( 130 ), ‘,’ , $str ); // baseline single quote
$str = str_replace ( chr ( 131 ), ‘NLG’ , $str ); // florin
$str = str_replace ( chr ( 132 ), ‘»‘ , $str ); // baseline double quote
$str = str_replace ( chr ( 133 ), ‘. ‘ , $str ); // ellipsis
$str = str_replace ( chr ( 134 ), ‘**’ , $str ); // dagger (a second footnote)
$str = str_replace ( chr ( 135 ), ‘***’ , $str ); // double dagger (a third footnote)
$str = str_replace ( chr ( 136 ), ‘^’ , $str ); // circumflex accent
$str = str_replace ( chr ( 137 ), ‘o/oo’ , $str ); // permile
$str = str_replace ( chr ( 138 ), ‘Sh’ , $str ); // S Hacek
$str = str_replace ( chr ( 139 ), ‘// $str = str_replace(chr(140), ‘OE’, $str); // OE ligature
$str = str_replace ( chr ( 145 ), «‘» , $str ); // left single quote
$str = str_replace ( chr ( 146 ), «‘» , $str ); // right single quote
// $str = str_replace(chr(147), ‘»‘, $str); // left double quote
// $str = str_replace(chr(148), ‘»‘, $str); // right double quote
$str = str_replace ( chr ( 149 ), ‘-‘ , $str ); // bullet
$str = str_replace ( chr ( 150 ), ‘-–’ , $str ); // endash
$str = str_replace ( chr ( 151 ), ‘—‘ , $str ); // emdash
// $str = str_replace(chr(152), ‘~’, $str); // tilde accent
// $str = str_replace(chr(153), ‘(TM)’, $str); // trademark ligature
$str = str_replace ( chr ( 154 ), ‘sh’ , $str ); // s Hacek
$str = str_replace ( chr ( 155 ), ‘>’ , $str ); // right single guillemet
// $str = str_replace(chr(156), ‘oe’, $str); // oe ligature
$str = str_replace ( chr ( 159 ), ‘Y’ , $str ); // Y Dieresis
$str = str_replace ( ‘°C’ , ‘°C’ , $str ); // Celcius is used quite a lot so it makes sense to add this in
$str = str_replace ( ‘£’ , ‘£’ , $str );
$str = str_replace ( «‘» , «‘» , $str );
$str = str_replace ( ‘»‘ , ‘»‘ , $str );
$str = str_replace ( ‘–’ , ‘–’ , $str );
8 years ago
nikolaz dot tang at hotmail dot com’s solution of using json_encode/decode is interesting, but a couple of issues to be aware of with it.
// From: nikolaz dot tang at hotmail dot com’s post
function str_replace_json ( $search , $replace , $subject ) return json_decode ( str_replace ( $search , $replace , json_encode ( $subject )));
>
?>
json_decode will return objects, where arrays are probably expected. This is easily remedied by adding 2nd parameter ‘true’ to json_decode.
$search and $replace could contain strings that match json encoding, which will either change the structure returned by this method, or break the json.
ie:
var_dump ( str_replace_json ( ‘»:»‘ , ‘»,»‘ , [ ‘this’ => ‘stuff’ ]));
var_dump ( str_replace_json ( ‘this»:»‘ , ‘this» : «thing», «with»:»‘ , [ ‘this’ => ‘stuff’ ]));
?>
13 years ago
Might be worth mentioning that a SIMPLE way to accomplish Example 2 (potential gotchas) is to simply start your «replacements» in reverse.
So instead of starting from «A» and ending with «E»:
$search = array( ‘A’ , ‘B’ , ‘C’ , ‘D’ , ‘E’ );
$replace = array( ‘B’ , ‘C’ , ‘D’ , ‘E’ , ‘F’ );
// replaces A to B, B to C, C to D, D to E, E to F (makes them all F)
// start from «E» and end with «A»:
$search = array( ‘E’ , ‘D’ , ‘C’ , ‘B’ , ‘A’ );
$replace = array( ‘F’ , ‘E’ , ‘D’ , ‘C’ , ‘B’ );
// replaces E to F, D to E, C to D, B to C, A to B (prevents from
// multiple replacements of already replaced values)
?>
So basically start from the «end» and put the replacements in an order where the «replaced value» won’t equal a value that exists later in the «search array».
9 years ago
«If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though. «
I think one important (and not at all vaguely theoretical) use-case is completely ignored here. Take, for example, the way the PDO handles parameter replacement.
If we have the following query:
«SELECT * FROM my_table WHERE (id = ? AND my_column = ? AND other_column = ?);»
The «?»s should be replaced by each successive variable in a $parameters array. That is EXACTLY the use case for «search» being a value and «replace» being an array.
Considering that this is not only a real-world example but also part of a core PHP functionality I find it very strange that it’s dismissed so easily here.
5 years ago
This is what happens when the search and replace arrays are different sizes:
$search = array( ‘a’ , ‘b’ , ‘c’ , ‘d’ , ‘e’ );
$replace = array( ‘A’ , ‘B’ , ‘C’ );
$subject = ‘abcdefg’ ;
echo str_replace ( $search , $replace , $subject );
// result: ‘ABCfg’
$search = array( ‘a’ , ‘b’ , ‘c’ );
$replace = array( ‘A’ , ‘B’ , ‘C’ , ‘D’ , ‘E’ );
$subject = ‘abcdefg’ ;
echo str_replace ( $search , $replace , $subject );
// result: ‘ABCdefg’
?>
No warning or error is generated in either of these cases.
13 years ago
Here’s a deep replace function allowing multi-dimensional arrays in $search, $replace and $subject. The keys and other structure of $subject are preserved.
// Auxiliary function:
function _replaceWithAnything ( $search , $replace , $subject ) if(! is_array ( $search ) || ! is_array ( $replace )) $search =array( $search );
$replace =array( $replace );
>
$match = array_search ( $subject , $search , true );
if( $match !== false && array_key_exists ( $match , $replace ))
$subject = $replace [ $match ];
return $subject ;
>
// Main function:
function deepReplace ( $search , $replace , $subject ) if(! is_array ( $subject ))
return _replaceWithAnything ( $search , $replace , $subject );
foreach( $subject as & $val ) if( is_array ( $val )) $val = deepReplace ( $search , $replace , $val );
continue;
>
$val = _replaceWithAnything ( $search , $replace , $val );
>
return $subject ;
>
?>
7 years ago
$myString = “It was the best of mine it was the worst of mine,”;
// Displays “It was the best of bananas, it was the worst of bananas,”
echo str_replace( “mine”, “bananas”, $myString );
If you want to know how many times the search string was replaced, pass in a variable as an optional
fourth argument. After the function runs, this variable holds the number of replacements:
$myString = “It was the best of mine, it was the worst of mine,”;
// Displays “It was the best of bananas, it was the worst of bananas,”
echo str_replace( “mine”, “bananas”, $myString, $num ) . “ < br/ >”;
// Displays “The text was replaced 2 times.”
echo “The text was replaced $num times. < br/ >”;
7 years ago
Decision to avoid problem «it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.»
// at first sort by length to have longest firstly
usort($urls,’sortByLen’);
foreach($replaces as $key => $replace) $text = str_replace($key,$replace, $text);
>
function sortByLen($a,$b) return strlen($b)-strlen($a);
>
Hope it will help others like me
11 years ago
/**
* Convert foreign 8859-1 characters into HTML entities.
*
* @param string $str
* The string being parsed.
*
* @return string
* The converted string.
*/
public static function convert_chars_to_entities ( $str )
<
$str = str_replace ( ‘À’ , ‘À’ , $str );
$str = str_replace ( ‘Á’ , ‘Á’ , $str );
$str = str_replace ( ‘Â’ , ‘Â’ , $str );
$str = str_replace ( ‘Ã’ , ‘Ã’ , $str );
$str = str_replace ( ‘Ä’ , ‘Ä’ , $str );
$str = str_replace ( ‘Å’ , ‘Å’ , $str );
$str = str_replace ( ‘Æ’ , ‘Æ’ , $str );
$str = str_replace ( ‘Ç’ , ‘Ç’ , $str );
$str = str_replace ( ‘È’ , ‘È’ , $str );
$str = str_replace ( ‘É’ , ‘É’ , $str );
$str = str_replace ( ‘Ê’ , ‘Ê’ , $str );
$str = str_replace ( ‘Ë’ , ‘Ë’ , $str );
$str = str_replace ( ‘Ì’ , ‘Ì’ , $str );
$str = str_replace ( ‘Í’ , ‘Í’ , $str );
$str = str_replace ( ‘Î’ , ‘Î’ , $str );
$str = str_replace ( ‘Ï’ , ‘Ï’ , $str );
$str = str_replace ( ‘Ð’ , ‘Ð’ , $str );
$str = str_replace ( ‘Ñ’ , ‘Ñ’ , $str );
$str = str_replace ( ‘Ò’ , ‘Ò’ , $str );
$str = str_replace ( ‘Ó’ , ‘Ó’ , $str );
$str = str_replace ( ‘Ô’ , ‘Ô’ , $str );
$str = str_replace ( ‘Õ’ , ‘Õ’ , $str );
$str = str_replace ( ‘Ö’ , ‘Ö’ , $str );
$str = str_replace ( ‘×’ , ‘×’ , $str ); // Yeah, I know. But otherwise the gap is confusing. —Kris
$str = str_replace ( ‘Ø’ , ‘Ø’ , $str );
$str = str_replace ( ‘Ù’ , ‘Ù’ , $str );
$str = str_replace ( ‘Ú’ , ‘Ú’ , $str );
$str = str_replace ( ‘Û’ , ‘Û’ , $str );
$str = str_replace ( ‘Ü’ , ‘Ü’ , $str );
$str = str_replace ( ‘Ý’ , ‘Ý’ , $str );
$str = str_replace ( ‘Þ’ , ‘Þ’ , $str );
$str = str_replace ( ‘ß’ , ‘ß’ , $str );
$str = str_replace ( ‘à’ , ‘à’ , $str );
$str = str_replace ( ‘á’ , ‘á’ , $str );
$str = str_replace ( ‘â’ , ‘â’ , $str );
$str = str_replace ( ‘ã’ , ‘ã’ , $str );
$str = str_replace ( ‘ä’ , ‘ä’ , $str );
$str = str_replace ( ‘å’ , ‘å’ , $str );
$str = str_replace ( ‘æ’ , ‘æ’ , $str );
$str = str_replace ( ‘ç’ , ‘ç’ , $str );
$str = str_replace ( ‘è’ , ‘è’ , $str );
$str = str_replace ( ‘é’ , ‘é’ , $str );
$str = str_replace ( ‘ê’ , ‘ê’ , $str );
$str = str_replace ( ‘ë’ , ‘ë’ , $str );
$str = str_replace ( ‘ì’ , ‘ì’ , $str );
$str = str_replace ( ‘í’ , ‘í’ , $str );
$str = str_replace ( ‘î’ , ‘î’ , $str );
$str = str_replace ( ‘ï’ , ‘ï’ , $str );
$str = str_replace ( ‘ð’ , ‘ð’ , $str );
$str = str_replace ( ‘ñ’ , ‘ñ’ , $str );
$str = str_replace ( ‘ò’ , ‘ò’ , $str );
$str = str_replace ( ‘ó’ , ‘ó’ , $str );
$str = str_replace ( ‘ô’ , ‘ô’ , $str );
$str = str_replace ( ‘õ’ , ‘õ’ , $str );
$str = str_replace ( ‘ö’ , ‘ö’ , $str );
$str = str_replace ( ‘÷’ , ‘÷’ , $str ); // Yeah, I know. But otherwise the gap is confusing. —Kris
$str = str_replace ( ‘ø’ , ‘ø’ , $str );
$str = str_replace ( ‘ù’ , ‘ù’ , $str );
$str = str_replace ( ‘ú’ , ‘ú’ , $str );
$str = str_replace ( ‘û’ , ‘û’ , $str );
$str = str_replace ( ‘ü’ , ‘ü’ , $str );
$str = str_replace ( ‘ý’ , ‘ý’ , $str );
$str = str_replace ( ‘þ’ , ‘þ’ , $str );
$str = str_replace ( ‘ÿ’ , ‘ÿ’ , $str );
9 years ago
// a very beatiful way to do multiple replacements is this one, using just one array
$replaceThis = Array(
‘old word’ => ‘new word’ ,
‘was’ => ‘it’ ,
‘past’ => ‘future’ ,
);
?php
$originalText = «every old word was a thing of the past. » ;
$replacedText = str_replace ( array_keys ( $replaceThis ), $replaceThis , $originalText );
echo $replacedText ;
?>
13 years ago
If we have a html template that contains placeholders in curly braces that need to be replaced in runtime, the following function will do it using str_replace:
Замена символов в строке php
Приведение к int возьмет числовую часть и отбросит всё остальное.
Еще вот так можно:
echo 0 + '300 руб'; // echo '300 руб' + 0;
Отслеживать
ответ дан 6 июл 2017 в 4:24
Алексей Шиманский Алексей Шиманский
71.9k 12 12 золотых знаков 91 91 серебряный знак 180 180 бронзовых знаков
Спасибо большое за помощь. int отличный способ, надо запомнить 🙂
6 июл 2017 в 4:43
-
Важное на Мете
Похожие
Подписаться на ленту
Лента вопроса
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2024 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2024.1.3.2953
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Как заменить символы в строке?
Вопрос: Как заменить в данной строке все символы до @ и исключить первый символ и последний до @, на * . То есть должно получиться вот так:
Как реализовать данную задачу?
Отслеживать
5,821 3 3 золотых знака 15 15 серебряных знаков 24 24 бронзовых знака
задан 17 июн 2018 в 9:47
438 1 1 золотой знак 6 6 серебряных знаков 20 20 бронзовых знаков
3 ответа 3
Сортировка: Сброс на вариант по умолчанию
$str /cdn-cgi/l/email-protection" data-cfemail="bccad9cecfc8ddd0ddfccbd9decfd5c8d992dfd3d1">[email protected]"; $pos = stripos($str, "@"); for($i=1; $i < $pos - 1; $i++) $str[$i] = "*"; echo $str; //Выводит v******[email protected]
Отслеживать
ответ дан 17 июн 2018 в 9:52
3,169 2 2 золотых знака 22 22 серебряных знака 44 44 бронзовых знака
$str /cdn-cgi/l/email-protection" data-cfemail="512734232225303d3011263433223825347f323e3c">[email protected]"; // При условии, что строка валидный мейл // Первая часть это имя пользователя, вторая адрес почты preg_match('/(?.+)@(?.+)/', $str, $matches); //---------------------------------------------------------------- // $matches['hide'][0] - первая буква $hide_name = $matches['hide'][0] . str_repeat("*", strlen($matches['hide']) - 1); // echo sprintf("%s@%s", $hide_name, $matches['addr']);
Отслеживать
ответ дан 17 июн 2018 в 22:37
5,821 3 3 золотых знака 15 15 серебряных знаков 24 24 бронзовых знака
Ещё вариант в коллекцию ответов:
$str = '[email protected]'; echo preg_replace_callback( '~(?<=[\pL\d]).+(?=[\pL\d]@)~', function($a)< return str_repeat('*', strlen($a[0])); >, $str );
Отслеживать
ответ дан 17 июн 2018 в 22:51
11.4k 4 4 золотых знака 18 18 серебряных знаков 28 28 бронзовых знаков
- php
- strlen
-
Важное на Мете
Похожие
Подписаться на ленту
Лента вопроса
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2024 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2024.1.3.2953
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.