Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

substr_replace

(PHP 4, PHP 5)

substr_replace -- Заменяет часть строки

Описание

string substr_replace ( string string, string replacement, int start [, int length] )

substr_replace() заменяет часть строки string начинающуюся с символа с порядковым номером start и длиной length строкой replacement и возвращает результат.

Если start - положительное число, замена начинается с символа с порядковым номером start.

Если start - отрицательное число, замена начинается с символа с порядковым номером start, считая от конца строки.

Если аргумент length - положительное число, то он определяет длину заменяемой подстроки. Если этот аргумент отрицательный, он определяет количество символов от конца строки, на котором заканчивается замена. Этот аргумент необязателен и по умолчанию равен strlen(string );, т.е. замена до конца строки string.

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

<?php
$var
= 'ABCDEFGH:/MNRPQR/';
echo
"Оригинал: $var<hr />\n";

/* Обе следующих строки заменяют всю строку $var на 'bob'. */
echo substr_replace($var, 'bob', 0) . "<br />\n";
echo
substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n";

/* Вставляет 'bob' в начало $var. */
echo substr_replace($var, 'bob', 0, 0) . "<br />\n";

/* Обе следующих строки заменяют 'MNRPQR' in $var на 'bob'. */
echo substr_replace($var, 'bob', 10, -1) . "<br />\n";
echo
substr_replace($var, 'bob', -7, -1) . "<br />\n";

/* Удаляет 'MNRPQR' из $var. */
echo substr_replace($var, '', 10, -1) . "<br />\n";
?>

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

См. также описание функций str_replace() и substr().



substr> <substr_count
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
substr_replace
alishahnovin at hotmail dot com
07-Aug-2007 12:56
I like the truncate function below...however, I found a few issues. Particularly if you have content that may have any kind of punctuation in it (?, !, ?!?, --, ..., .., ;, etc.)

The older function would end up looking like "blah blah?..." or "blah blah,..." which doesn't look so nice to me...

Here's my fix. It removes all trailing punctuation (that you include in the $punctuation string below) and then adds an ellipse. So even if it has an ellipse with 3 dots, 2 dots, 4 dots, it'll be removed, then re-added.

<?php
function truncate($text,$numb,$etc = "...") {
$text = html_entity_decode($text, ENT_QUOTES);
if (
strlen($text) > $numb) {
$text = substr($text, 0, $numb);
$text = substr($text,0,strrpos($text," "));

$punctuation = ".!?:;,-"; //punctuation you want removed

$text = (strspn(strrev($text),  $punctuation)!=0)
        ?
       
substr($text, 0, -strspn(strrev($text),  $punctuation))
        :
$text;

$text = $text.$etc;
}
$text = htmlentities($text, ENT_QUOTES);
return
$text;
}
?>

I also needed a sort of "middle" truncate. The above function truncates around the end, but if you want to truncate around the middle (ie "Hello this is a long string." --> "Hello this ... long string.") you can use this (requires the truncate function):

<?php
function mtruncate($text, $numb, $etc = " ... ") {
   
$first_part = truncate(truncate($text, strlen($text)/2, ""), $numb/2, "");
   
$second_part = truncate(strrev(truncate(strrev($text), strlen($text)/2, "")), $numb/2, "");
    return
$first_part.$etc.$second_part;
}
?>
joecorcoran at gmail dot com
07-Aug-2007 06:50
I've made a minor amendment to the function in the post below, to strip away the full stop (period) if the truncation occurs at the exact end of a sentence (the full stop spoils the ellipsis):

<?php

function truncate($text,$numb) {
$text = html_entity_decode($text, ENT_QUOTES);
if (
strlen($text) > $numb) {
$text = substr($text, 0, $numb);
$text = substr($text,0,strrpos($text," "));
   
//This strips the full stop:
   
if ((substr($text, -1)) == ".") {
       
$text = substr($text,0,(strrpos($text,".")));
    }
$etc = "...";
$text = $text.$etc;
}
$text = htmlentities($text, ENT_QUOTES);
return
$text;
}

//Call function
truncate($text, 75);
www.kigoobe.com
21-Mar-2007 03:00
The two truncate functions provided below, have some major short comings.

1. They may cut a word in half
2. In case you are using htmlentities to get user input or are using wysiwyg editors to get user input, you can get truncated text like "he told C&eac..." instead of "he told C
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571