Как получить число из строки php
В PHP, строка ( string ) считается числовой, если её можно интерпретировать как целое ( int ) число или как число с плавающей точкой ( float ).
Формально с PHP 8.0.0:
WHITESPACES \s* LNUM [0-9]+ DNUM ([0-9]*[\.]) | ([\.][0-9]*) EXPONENT_DNUM (( | ) [eE][+-]? ) INT_NUM_STRING [+-]? FLOAT_NUM_STRING [+-]? ( | ) NUM_STRING ( | )
В PHP также присутствует концепция префиксной числовой строки. Это строка, которая начинается как числовая и продолжается любыми другими символами.
Замечание:
Любая строка, содержащая букву E (без учёта регистра), ограниченную цифрами, будет восприниматься как число, выраженное в научной нотации. Это может привести к неожиданным результатам.
var_dump ( «0D1» == «000» ); // false, «0D1» не является научной нотацией
var_dump ( «0E1» == «000» ); // true, «0E1» — это 0 * (10 ^ 1) или 0
var_dump ( «2E1» == «020» ); // true, «2E1» — это 2 * (10 ^ 1) или 20
?>?php
Строки, используемые в числовых контекстах
- Если строка числовая, представляет целое число и не превышает максимально допустимого значения для типа int (определённого в PHP_INT_MAX ), то она приводится к типу int . Иначе она приводится к типу float .
- Если в заданном контексте дозволительно использовать префиксную числовую строку, то, если начало строки представляет целое число и не превышает максимально допустимого значения для типа int (определённого в PHP_INT_MAX ), то она приводится к типу int . Иначе она приводится к типу float . Также, в этом случае, выдаётся ошибка уровня E_WARNING .
- Если строка не числовая — выбрасывается исключение TypeError .
Поведение до PHP 8.0.0
До PHP 8.0.0, строка считалась числовой только в случае, если она начиналась с пробельных символов. Если она завершалась пробельными символами — она считалась префиксной числовой.
- Использование префиксной числовой строки вызывало ошибку уровня E_NOTICE , а не E_WARNING .
- Если строка не являлась числовой, вызывалась ошибка уровня E_WARNING , а сама строка приводилась к числу 0 .
$foo = 1 + «10.5» ; // $foo считается за число с плавающей точкой (11.5)
$foo = 1 + «-1.3e3» ; // $foo считается за число с плавающей точкой (-1299)
$foo = 1 + «bob-1.3e3» ; // TypeError начиная с PHP 8.0.0. В более ранних версиях $foo считалось за целое число (1)
$foo = 1 + «bob3» ; // TypeError начиная с PHP 8.0.0, В более ранних версиях $foo считалось за целое число (1)
$foo = 1 + «10 Small Pigs» ; // $foo — целое (11). В PHP 8.0.0 создаётся ошибка уровня E_WARNING, а в более ранних версиях уровня E_NOTICE
$foo = 4 + «10.2 Little Piggies» ; // $foo — число с плавающей точкой (14.2). В PHP 8.0.0 создаётся ошибка уровня E_WARNING, а в более ранних версиях уровня E_NOTICE
$foo = «10.0 pigs » + 1 ; // $foo — число с плавающей точкой (11). В PHP 8.0.0 создаётся ошибка уровня E_WARNING, а в более ранних версиях уровня E_NOTICE
$foo = «10.0 pigs » + 1.0 ; // $foo — число с плавающей точкой (11). В PHP 8.0.0 создаётся ошибка уровня E_WARNING, а в более ранних версиях уровня E_NOTICE
?>?php
User Contributed Notes
There are no user contributed notes for this page.
- Типы
- Введение
- Система типов
- NULL
- Логический тип
- Целые числа
- Числа с плавающей точкой
- Строки
- Числовые строки
- Массивы
- Объекты
- Перечисления
- Ресурс
- Функции обратного вызова (callback-функции)
- Mixed
- Void
- Never
- Относительные типы классов
- Value types
- Итерируемые
- Объявление типов
- Манипуляции с типами
Извлечь числа из строки в PHP
В этой статье показано, как извлекать числа из строки в PHP.
1. Использование preg_replace() функция
Идея состоит в том, чтобы идентифицировать все нечисловые символы в строке и заменить их пустой строкой ( «» ). В PHP это можно сделать с помощью preg_replace() функция. Вы можете использовать регулярное выражение \D+ или же [^0-9]+ чтобы соответствовать одному или нескольким нечисловым символам, которые можно легко изменить, чтобы извлечь любые дополнительные символы из строки (например, + , — , . , , ):
$str = ‘X:+2.15, Y:-1.50, Z:0’ ;
var_dump ( preg_replace ( ‘/\D+/’ , » , $str ) ) ;
Вывод: строка(5) «2151500»
var_dump ( preg_replace ( ‘/[^0-9-\+\.,]+/’ , » , $str ) ) ;
Вывод: строка(5) строка(13) «+2.15,-1.50,0»Вы можете использовать preg_match_all() для получения массива всех совпадений, как показано ниже. Здесь, \d+ соответствует одному или нескольким числовым символам.
$str = ‘X:+2.15, Y:-1.50, Z:0’ ;
preg_match_all ( ‘/\d+/’ , $str , $matches ) ;
print_r ( $matches [ 0 ] ) ;
preg_match_all ( ‘/(\+|-)<0,1>\d+\.<0,1>\d*/’ , $str , $matches ) ;0,1>
print_r ( $matches [ 0 ] ) ;2. Использование filter_var() функция
PHP имеет встроенную функцию, называемую filter_var() который фильтрует переменную с указанным фильтром. FILTER_SANITIZE_NUMBER_FLOAT фильтр удаляет все символы из строки, кроме цифр, плюс и минус, и, возможно, eE . Этот фильтр также удалит десятичный символ ( . ) пока не FILTER_FLAG_ALLOW_FRACTION указан флаг. Вы также можете использовать FILTER_SANITIZE_NUMBER_INT который также удаляет все символы из строки, кроме цифр и +/- , но не принимает никаких флагов.
substr_count
substr_count() возвращает число вхождений подстроки needle в строку haystack . Заметьте, что параметр needle чувствителен к регистру.
Замечание:
Эта функция не подсчитывает перекрывающиеся подстроки. Смотрите пример ниже!
Список параметров
Строка, в которой ведётся поиск
Смещение начала отсчёта. Если задано отрицательное значение, отсчёт позиции будет произведён с конца строки.
Максимальная длина строки, в которой будет производится поиск подстроки после указанного смещения. Если сумма смещения и максимальной длины будет больше длины haystack , то будет выведено предупреждение. Отрицательное значение будет отсчитываться с конца haystack .
Возвращаемые значения
Эта функция возвращает целое число ( int ).
Список изменений
Версия Описание 8.0.0 length теперь допускает значение null. 7.1.0 Добавлена поддержка отрицательных значений offset и length . length теперь также может быть 0 . Примеры
Пример #1 Пример использования substr_count()
$text = ‘This is a test’ ;
echo strlen ( $text ); // 14?php
echo substr_count ( $text , ‘is’ ); // 2
// строка уменьшается до ‘s is a test’, поэтому вывод будет 1
echo substr_count ( $text , ‘is’ , 3 );// текст уменьшается до ‘s i’, поэтому вывод будет 0
echo substr_count ( $text , ‘is’ , 3 , 3 );// генерирует предупреждение, так как 5+10 > 14
echo substr_count ( $text , ‘is’ , 5 , 10 );// выводит только 1, т.к. перекрывающиеся подстроки не учитываются
$text2 = ‘gcdgcdgcd’ ;
echo substr_count ( $text2 , ‘gcdgcd’ );
?>Смотрите также
- count_chars() — Возвращает информацию о символах, входящих в строку
- strpos() — Возвращает позицию первого вхождения подстроки
- substr() — Возвращает подстроку
- strstr() — Находит первое вхождение подстроки
User Contributed Notes 10 notes
7 years ago
It’s worth noting this function is surprisingly fast. I first ran it against a ~500KB string on our web server. It found 6 occurrences of the needle I was looking for in 0.0000 seconds. Yes, it ran faster than microtime() could measure.
Looking to give it a challenge, I then ran it on a Mac laptop from 2010 against a 120.5MB string. For one test needle, it found 2385 occurrences in 0.0266 seconds. Another test needs found 290 occurrences in 0.114 seconds.
Long story short, if you’re wondering whether this function is slowing down your script, the answer is probably not.
17 years ago
Making this case insensitive is easy for anyone who needs this. Simply convert the haystack and the needle to the same case (upper or lower).
8 years ago
To account for the case that jrhodes has pointed out, we can change the line to:
substr_count ( implode( ‘,’, $haystackArray ), $needle );
array (
0 => «mystringth»,
1 => «atislong»
);Which brings the count for $needle = «that» to 0 again.
14 years ago
It was suggested to use
substr_count ( implode( $haystackArray ), $needle );
instead of the function described previously, however this has one flaw. For example this array:
array (
0 => «mystringth»,
1 => «atislong»
);If you are counting «that», the implode version will return 1, but the function previously described will return 0.
19 years ago
Yet another reference to the «cgcgcgcgcgcgc» example posted by «chris at pecoraro dot net»:
Your request can be fulfilled with the Perl compatible regular expressions and their lookahead and lookbehind features.
$number_of_full_pattern = preg_match_all(‘/(cgc)/’, «cgcgcgcgcgcgcg», $chunks);
works like the substr_count function. The variable $number_of_full_pattern has the value 3, because the default behavior of Perl compatible regular expressions is to consume the characters of the string subject that were matched by the (sub)pattern. That is, the pointer will be moved to the end of the matched substring.
But we can use the lookahead feature that disables the moving of the pointer:$number_of_full_pattern = preg_match_all(‘/(cg(?=c))/’, «cgcgcgcgcgcgcg», $chunks);
In this case the variable $number_of_full_pattern has the value 6.
Firstly a string «cg» will be matched and the pointer will be moved to the end of this string. Then the regular expression looks ahead whether a ‘c’ can be matched. Despite of the occurence of the character ‘c’ the pointer is not moved.16 years ago
a simple version for an array needle (multiply sub-strings):
function substr_count_array ( $haystack , $needle ) $count = 0 ;
foreach ( $needle as $substring ) $count += substr_count ( $haystack , $substring );
>
return $count ;
>
?>10 years ago
Unicode example with «case-sensitive» option;
function substr_count_unicode ( $str , $substr , $caseSensitive = true , $offset = 0 , $length = null ) if ( $offset ) $str = substr_unicode ( $str , $offset , $length );
>$pattern = $caseSensitive
? ‘~(?:’ . preg_quote ( $substr ) . ‘)~u’
: ‘~(?:’ . preg_quote ( $substr ) . ‘)~ui’ ;
preg_match_all ( $pattern , $str , $matches );return isset( $matches [ 0 ]) ? count ( $matches [ 0 ]) : 0 ;
>function substr_unicode ( $str , $start , $length = null ) return join ( » , array_slice (
preg_split ( ‘~~u’ , $str , — 1 , PREG_SPLIT_NO_EMPTY ), $start , $length ));
>$s = ‘Ümit yüzüm gözüm. ‘ ;
print substr_count_unicode ( $s , ‘ü’ ); // 3
print substr_count_unicode ( $s , ‘ü’ , false ); // 4
print substr_count_unicode ( $s , ‘ü’ , false , 10 ); // 1print substr_count_unicode ( $s , ‘üm’ ); // 2
print substr_count_unicode ( $s , ‘üm’ , false ); // 3
?>9 years ago
This will handle a string where it is unknown if comma or period are used as thousand or decimal separator. Only exception where this leads to a conflict is when there is only a single comma or period and 3 possible decimals (123.456 or 123,456). An optional parameter is passed to handle this case (assume thousands, assume decimal, decimal when period, decimal when comma). It assumes an input string in any of the formats listed below.
function toFloat($pString, $seperatorOnConflict=»f»)
$decSeperator=».»;
$thSeperator=»»;$pString=str_replace(» «, $thSeperator, $pString);
$firstPeriod=strpos($pString, «.»);
$firstComma=strpos($pString, «,»);
if($firstPeriod!==FALSE && $firstComma!==FALSE) if($firstPeriod <$firstComma) $pString=str_replace(".", $thSeperator, $pString);
$pString=str_replace(«,», $decSeperator, $pString);
>
else $pString=str_replace(«,», $thSeperator, $pString);
>
>
else if($firstPeriod!==FALSE || $firstComma!==FALSE) $seperator=$firstPeriod!==FALSE?».»:»,»;
if(substr_count($pString, $seperator)==1) $lastPeriodOrComma=strpos($pString, $seperator);
if($lastPeriodOrComma==(strlen($pString)-4) && ($seperatorOnConflict!=$seperator && $seperatorOnConflict!=»f»)) $pString=str_replace($seperator, $thSeperator, $pString);
>
else $pString=str_replace($seperator, $decSeperator, $pString);
>
>
else $pString=str_replace($seperator, $thSeperator, $pString);
>
>
return(float)$pString;
>substr
Возвращает подстроку строки string , начинающейся с offset символа по счету и длиной length символов.
Список параметров
Если offset неотрицателен, возвращаемая подстрока начинается с позиции offset от начала строки, считая от нуля. Например, в строке ‘ abcdef ‘, в позиции 0 находится символ ‘ a ‘, в позиции 2 — символ ‘ c ‘, и т.д.
Если offset отрицательный, возвращаемая подстрока начинается с позиции, отстоящей на offset символов от конца строки string .
Если string меньше offset символов, будет возвращена пустая строка.
Пример #1 Использование отрицательного параметра offset
$rest = substr ( «abcdef» , — 1 ); // возвращает «f»
$rest = substr ( «abcdef» , — 2 ); // возвращает «ef»
$rest = substr ( «abcdef» , — 3 , 1 ); // возвращает «d»
?>?phpЕсли length положительный, возвращаемая строка будет не длиннее length символов, начиная с параметра offset (в зависимости от длины string ).
Если length отрицательный, то будет отброшено указанное этим аргументом число символов с конца строки string (после того как будет вычислена стартовая позиция, если offset отрицателен). Если при этом позиция начала подстроки, определяемая аргументом offset , находится в отброшенной части строки или за ней, возвращается пустая строка.
Если параметр length задан и равен 0 , будет возвращена пустая строка.
Если параметр length опущен или null , то будет возвращена подстрока, начинающаяся с позиции, указанной параметром offset и длящейся до конца строки.
Пример #2 Использование отрицательного параметра length
$rest = substr ( «abcdef» , 0 , — 1 ); // возвращает «abcde»
$rest = substr ( «abcdef» , 2 , — 1 ); // возвращает «cde»
$rest = substr ( «abcdef» , 4 , — 4 ); // возвращает «»; до PHP 8.0.0 возвращалось false
$rest = substr ( «abcdef» , — 3 , — 1 ); // возвращает «de»
?>?phpВозвращаемые значения
Возвращает извлечённую часть параметра string или пустую строку.
Список изменений
Версия Описание 8.0.0 Параметр length теперь допускает значение null. Если значение параметра length явно задано как null , функция возвращает подстроку, заканчивающуюся в конце строки; ранее возвращалась пустая строка. 8.0.0 Функция возвращает пустую строку там, где раньше возвращала false . Примеры
Пример #3 Базовое использование substr()
echo substr ( ‘abcdef’ , 1 ); // bcdef
echo substr ( «abcdef» , 1 , null ); // bcdef; до PHP 8.0.0 возвращалась пустая строка
echo substr ( ‘abcdef’ , 1 , 3 ); // bcd
echo substr ( ‘abcdef’ , 0 , 4 ); // abcd
echo substr ( ‘abcdef’ , 0 , 8 ); // abcdef
echo substr ( ‘abcdef’ , — 1 , 1 ); // f?php
// Получить доступ к отдельному символу в строке
// можно также с помощью квадратных скобок
$string = ‘abcdef’ ;
echo $string [ 0 ]; // a
echo $string [ 3 ]; // d
echo $string [ strlen ( $string )- 1 ]; // fПример #4 substr() и приведение типов
class apple public function __toString () return «green» ;
>
>?php
echo «1) » . var_export ( substr ( «pear» , 0 , 2 ), true ). PHP_EOL ;
echo «2) » . var_export ( substr ( 54321 , 0 , 2 ), true ). PHP_EOL ;
echo «3) » . var_export ( substr (new apple (), 0 , 2 ), true ). PHP_EOL ;
echo «4) » . var_export ( substr ( true , 0 , 1 ), true ). PHP_EOL ;
echo «5) » . var_export ( substr ( false , 0 , 1 ), true ). PHP_EOL ;
echo «6) » . var_export ( substr ( «» , 0 , 1 ), true ). PHP_EOL ;
echo «7) » . var_export ( substr ( 1.2e3 , 0 , 4 ), true ). PHP_EOL ;
?>Результат выполнения данного примера:
1) 'pe' 2) '54' 3) 'gr' 4) '1' 5) '' 6) '' 7) '1200'
Пример #5 Недопустимый диапазон символов
Если запрашивается недопустимый диапазон символов, substr() возвращает пустую строку, начиная с PHP 8.0.0; ранее возвращалось false .
var_dump ( substr ( ‘a’ , 2 ));
?>?phpРезультат выполнения данного примера в PHP 8:
string(0) ""
Результат выполнения данного примера в PHP 7:
bool(false)
Смотрите также
- strrchr() — Находит последнее вхождение символа в строке
- substr_replace() — Заменяет часть строки
- preg_match() — Выполняет проверку на соответствие регулярному выражению
- trim() — Удаляет пробелы (или другие символы) из начала и конца строки
- mb_substr() — Возвращает часть строки
- wordwrap() — Переносит строку по указанному количеству символов
- Посимвольный доступ и изменение строки
User Contributed Notes 36 notes
14 years ago
For getting a substring of UTF-8 characters, I highly recommend mb_substr
echo substr ( $utf8string , 0 , 5 );
// output cake#
echo mb_substr ( $utf8string , 0 , 5 , ‘UTF-8’ );
//output cakeæ
?>10 years ago
may be by following functions will be easier to extract the needed sub parts from a string:
after ( ‘@’ , ‘biohazard@online.ge’ );
//returns ‘online.ge’
//from the first occurrence of ‘@’before ( ‘@’ , ‘biohazard@online.ge’ );
//returns ‘biohazard’
//from the first occurrence of ‘@’between ( ‘@’ , ‘.’ , ‘biohazard@online.ge’ );
//returns ‘online’
//from the first occurrence of ‘@’after_last ( ‘[‘ , ‘sin[90]*cos[180]’ );
//returns ‘180]’
//from the last occurrence of ‘[‘before_last ( ‘[‘ , ‘sin[90]*cos[180]’ );
//returns ‘sin[90]*cos[‘
//from the last occurrence of ‘[‘between_last ( ‘[‘ , ‘]’ , ‘sin[90]*cos[180]’ );
//returns ‘180’
//from the last occurrence of ‘[‘
?>here comes the source:
function after ( $this , $inthat )
if (! is_bool ( strpos ( $inthat , $this )))
return substr ( $inthat , strpos ( $inthat , $this )+ strlen ( $this ));
>;function after_last ( $this , $inthat )
if (! is_bool ( strrevpos ( $inthat , $this )))
return substr ( $inthat , strrevpos ( $inthat , $this )+ strlen ( $this ));
>;function before ( $this , $inthat )
return substr ( $inthat , 0 , strpos ( $inthat , $this ));
>;function before_last ( $this , $inthat )
return substr ( $inthat , 0 , strrevpos ( $inthat , $this ));
>;function between ( $this , $that , $inthat )
return before ( $that , after ( $this , $inthat ));
>;function between_last ( $this , $that , $inthat )
return after_last ( $this , before_last ( $that , $inthat ));
>;// use strrevpos function in case your php version does not include it
function strrevpos ( $instr , $needle )
$rev_pos = strpos ( strrev ( $instr ), strrev ( $needle ));
if ( $rev_pos === false ) return false ;
else return strlen ( $instr ) — $rev_pos — strlen ( $needle );
>;
?>6 years ago
Be aware of a slight inconsistency between substr and mb_substr
mb_substr(«», 4); returns empty string
substr(«», 4); returns boolean false
tested in PHP 7.1.11 (Fedora 26) and PHP 5.4.16 (CentOS 7.4)
10 years ago
### SUB STRING BY WORD USING substr() and strpos() #####
### THIS SCRIPT WILL RETURN PART OF STRING WITHOUT WORD BREAK ###
$description = ‘your description here your description here your description here your description here your description here your description here your description hereyour description here your description here’ // your description here .
if( strlen ( $desctiption ) > 30 )
echo substr ( $description , 0 , strpos ( $description , ’ ‘ , 30 )); //strpos to find ‘ ‘ after 30 characters.
>
else echo $description ;
>9 years ago
Coming to PHP from classic ASP I am used to the Left() and Right() functions built into ASP so I did a quick PHPversion. hope these help someone else making the switch
function left($str, $length) return substr($str, 0, $length);
>function right($str, $length) return substr($str, -$length);
>12 years ago
If you want to have a string BETWEEN two strings, just use this function:
function get_between ( $input , $start , $end )
<
$substr = substr ( $input , strlen ( $start )+ strpos ( $input , $start ), ( strlen ( $input ) — strpos ( $input , $end ))*(- 1 ));
return $substr ;
>$string = «123456789» ;
$a = «12» ;
$b = «9» ;echo get_between ( $string , $a , $b );
18 years ago
This returns the portion of str specified by the start and length parameters..
It can performs multi-byte safe on number of characters. like mb_strcut() .Note:
1.Use it like this bite_str(string str, int start, int length [,byte of on string]);
2.First character’s position is 0. Second character position is 1, and so on.
3.$byte is one character length of your encoding, For example: utf-8 is «3», gb2312 and big5 is «2». you can use the function strlen() get it.
Enjoy it 🙂 .PS:I’m sorry my english is too poor. 🙁
// String intercept By Bleakwind
// utf-8:$byte=3 | gb2312:$byte=2 | big5:$byte=2
function bite_str ( $string , $start , $len , $byte = 3 )
$str = «» ;
$count = 0 ;
$str_len = strlen ( $string );
for ( $i = 0 ; $i < $str_len ; $i ++) if (( $count + 1 - $start )> $len ) $str .= «. » ;
break;
> elseif (( ord ( substr ( $string , $i , 1 )) <= 128 ) && ( $count < $start )) $count ++;
> elseif (( ord ( substr ( $string , $i , 1 )) > 128 ) && ( $count < $start )) $count = $count + 2 ;
$i = $i + $byte — 1 ;
> elseif (( ord ( substr ( $string , $i , 1 )) = $start )) $str .= substr ( $string , $i , 1 );
$count ++;
> elseif (( ord ( substr ( $string , $i , 1 )) > 128 ) && ( $count >= $start )) $str .= substr ( $string , $i , $byte );
$count = $count + 2 ;
$i = $i + $byte — 1 ;
>
>
return $str ;
>// Test
$str = «123456. ֽ?123456?ַ. 123456??ȡ. » ;
for( $i = 0 ; $i < 30 ; $i ++)echo "
» . bite_str ( $str , $i , 20 );
>
?>9 years ago
[English]
I created python similar accesing list or string with php substr & strrev functions.About of pattern structures
[start:stop:step]Example,
$s = «fatihmertdogancan» ;
echo str ( $s , «1:9:-2» );
echo «
» ;
echo str ( $s , «1:-3:-2» );
echo «
» ;
echo str ( $s , «1:-11:-5» );
echo «
» ;
echo str ( $s , «1:9:4» );
?>Output,
thetoacn
eht
aom
htanfunction str ( $str , $pattern ) //[start:stop:step]
//pattern -> ([-]?[0-9]*|\s):([-]?[0-9]*|\s):([-]?[0-9]*|\s)
preg_match ( «/([-]?[0-9]*|\s?):([-]?[0-9]*|\s?):?([-]?[0-9]*|\s?)/» , $pattern , $yakala );
$start = $yakala [ 1 ];
$stop = $yakala [ 2 ];
$step = $yakala [ 3 ];if(empty( $start ) && empty( $stop ) && empty( $step )) return $str ;
//»hepsi boş»;
>else if(empty( $start )) if(isset( $stop ) && empty( $step )) $rev = «» ;
if( $stop [ 0 ] == «-» )< $rev = "VAR" ;>
if( $rev != «VAR» ) return substr ( $str , 0 , $stop );
//»start ve step boş, stop dolu»
>else return strrev ( substr ( $str , 0 , $stop ));
//»start ve step boş, stop -1″;
>
>else if(isset( $stop ) && isset( $step )) $rev = «» ;
if( $stop [ 0 ] == «-» )< $rev = "VAR" ;>
$yeni = «» ;
if( $step == 1 ) if( $rev != «VAR» ) return $str ;
//»start boş, stop ve step dolu, step 1″;
>else return strrev ( substr ( $str , 0 , abs ( $stop ))); //abs -> mutlak değer (-5 = 5)
//»start boş, stop -, step dolu, step 1″;
>
>else $atla = abs ( $step );
for( $i = 0 ; $i <= strlen ( $str ); $i ++)$offset = $i * $atla ;
if(isset( $str [ $offset ])) $yeni = $yeni . $str [ $offset ];
>
>
if( $rev != «VAR» ) return substr ( $yeni , 0 , $stop );
//»start boş, step ve stop dolu»;
>else return strrev ( substr ( $yeni , 0 , abs ( $stop )));
//»start boş, step ve stop -«;
>
>
>
//start boş değilse
>else if(!empty( $start )) if(isset( $stop ) && empty( $step )) $rev = «» ;
if( $stop [ 0 ] == «-» )< $rev = "VAR" ;>
if( $rev != «VAR» ) return substr ( $str , $start , $stop );
//return «step boş, start ve stop dolu»;
>else return strrev ( substr ( $str , 0 , abs ( $stop )));
//»step boş, start ve stop dolu, stop -«;
>
>else if(isset( $stop ) && isset( $step ))//hepsi dolu
$rev = «» ;
if( $stop [ 0 ] == «-» )< $rev = "VAR" ;>
$yeni = «» ;
if( $step == 1 ) if( $rev != «VAR» ) return substr ( $str , $start , $stop );
//»hepsi dolu, step 1″;
>else return substr ( $str , $start , abs ( $stop ));
//»hepsi dolu, step 1, stop -«;
>
>else if( $stop [ 0 ] == «-» )< $rev = "VAR" ;>
$atla = abs ( $step );
for( $i = 0 ; $i <= strlen ( $str ); $i ++)$offset = $i * $atla ;
if(isset( $str [ $offset ])) $yeni = $yeni . $str [ $offset ];
>
>
if( $rev != «VAR» ) return substr ( $yeni , $start , $stop );
//»hepsi dolu»;
>else return strrev ( substr ( $yeni , $start , abs ( $stop )));
//»hepsi dolu, stop -«;
>
>
>
>
>
?>Good works..
14 years ago
Drop extensions of a file (even from a file location string)
$filename = «c:/some dir/abc defg. hi.jklmn» ;
echo substr ( $filename , 0 , ( strlen ( $filename )) — ( strlen ( strrchr ( $filename , ‘.’ ))));
?>
output: c:/some dir/abc defg. hi
Hope it may help somebody like me.. (^_^)
16 years ago
I wanted to work out the fastest way to get the first few characters from a string, so I ran the following experiment to compare substr, direct string access and strstr:
/* substr access */
beginTimer ();
for ( $i = 0 ; $i < 1500000 ; $i ++)$opening = substr ( $string , 0 , 11 );
if ( $opening == ‘Lorem ipsum’ ) true ;
>else false ;
>
>
$endtime1 = endTimer ();/* strstr access */
beginTimer ();
for ( $i = 0 ; $i < 1500000 ; $i ++)$opening = strstr ( $string , 'Lorem ipsum' );
if ( $opening == true ) true ;
>else false ;
>
>
$endtime3 = endTimer ();echo $endtime1 . «\r\n» . $endtime2 . «\r\n» . $endtime3 ;
?>The string was 6 paragraphs of Lorem Ipsum, and I was trying match the first two words. The experiment was run 3 times and averaged. The results were:
(substr) 3.24
(direct access) 11.49
(strstr) 4.96(With standard deviations 0.01, 0.02 and 0.04)
THEREFORE substr is the fastest of the three methods for getting the first few letters of a string.
14 years ago
I created some functions for entity-safe splitting+lengthcounting:
function strlen_entities ( $text )
preg_match_all (
‘/((?:&(?:#[0-9]|[a-z]);)|(?:[^&])|’ .
‘(?:&(?!\w;)))s’ , $text , $textarray );
return count ( $textarray [ 0 ]);
>
function substr_entities ( $text , $start , $limit = 0 )
$return = » ;
preg_match_all (
‘/((?:&(?:#[0-9]|[a-z]);)|(?:[^&])|’ .
‘(?:&(?!\w;)))s’ , $text , $textarray );
$textarray = $textarray [ 0 ];
$numchars = count ( $textarray )- 1 ;
if ( $start >= $numchars )
return false ;
if ( $start < 0 )
$start = ( $numchars )+ $start + 1 ;
>
if ( $start >= 0 )
if ( $limit == 0 )
$end = $numchars ;
>
elseif ( $limit > 0 )
$end = $start +( $limit — 1 );
>
else
$end = ( $numchars )+ $limit ;
>11 years ago
Using a 0 as the last parameter for substr().
As per examples
works no problem. However
will get you nothing. Just a quick heads up
14 years ago
Shortens the filename and its expansion has seen.
function funclongwords ( $file )
<
if ( strlen ( $file ) > 30 )
<
$vartypesf = strrchr ( $file , «.» );
$vartypesf_len = strlen ( $vartypesf );
$word_l_w = substr ( $file , 0 , 15 );
$word_r_w = substr ( $file ,- 15 );
$word_r_a = substr ( $word_r_w , 0 ,- $vartypesf_len );return $word_l_w . «. » . $word_r_a . $vartypesf ;
>
else
return $file ;
>
// RETURN: Hellothisfileha. andthisfayl.exe
?>18 years ago
Hmm . this is a script I wrote, whitch is very similar to substr, but it isn’t takes html and bbcode for counting and it takes portion of string and show avoided (html & bbcode) tags too ;]
Specially usefull for show part of serach result included html and bbcode tags/**
* string csubstr ( string string, int start [, int length] )
*
* @author FanFataL
* @param string string
* @param int start
* @param [int length]
* @return string
*/
function csubstr ( $string , $start , $length = false ) <
$pattern = ‘/(\[\w+[^\]]*?\]|\[\/\w+\]|<\w+[^>]*?>|)/i’ ;
$clean = preg_replace ( $pattern , chr ( 1 ), $string );
if(! $length )
$str = substr ( $clean , $start );
else <
$str = substr ( $clean , $start , $length );
$str = substr ( $clean , $start , $length + substr_count ( $str , chr ( 1 )));
>
$pattern = str_replace ( chr ( 1 ), ‘(.*?)’ , preg_quote ( $str ));
if( preg_match ( ‘/’ . $pattern . ‘/is’ , $string , $matched ))
return $matched [ 0 ];
return $string ;
>?>
Using this is similar to simple substr.
12 years ago
Anyone coming from the Python world will be accustomed to making substrings by using a «slice index» on a string. The following function emulates basic Python string slice behavior. (A more elaborate version could be made to support array input as well as string, and the optional third «step» argument.)
function py_slice ( $input , $slice ) $arg = explode ( ‘:’ , $slice );
$start = intval ( $arg [ 0 ]);
if ( $start < 0 ) $start += strlen ( $input );
>
if ( count ( $arg ) === 1 ) return substr ( $input , $start , 1 );
>
if ( trim ( $arg [ 1 ]) === » ) return substr ( $input , $start );
>
$end = intval ( $arg [ 1 ]);
if ( $end < 0 ) $end += strlen ( $input );
>
return substr ( $input , $start , $end — $start );
>print py_slice ( ‘abcdefg’ , ‘2’ ) . «\n» ;
print py_slice ( ‘abcdefg’ , ‘2:4’ ) . «\n» ;
print py_slice ( ‘abcdefg’ , ‘2:’ ) . «\n» ;
print py_slice ( ‘abcdefg’ , ‘:4’ ) . «\n» ;
print py_slice ( ‘abcdefg’ , ‘:-3’ ) . «\n» ;
print py_slice ( ‘abcdefg’ , ‘-3:’ ) . «\n» ;?>
The $slice parameter can be a single character index, or a range separated by a colon. The start of the range is inclusive and the end is exclusive, which may be counterintuitive. (Eg, py_slice(‘abcdefg’, ‘2:4’) yields ‘cd’ not ‘cde’). A negative range value means to count from the end of the string instead of the beginning. Both the start and end of the range may be omitted; the start defaults to 0 and the end defaults to the total length of the input.
The output from the examples:
c
cd
cdefg
abcd
abcd
efg17 years ago
/**
* string substrpos(string $str, mixed $start [[, mixed $end], boolean $ignore_case])
*
* If $start is a string, substrpos will return the string from the position of the first occuring $start to $end
*
* If $end is a string, substrpos will return the string from $start to the position of the first occuring $end
*
* If the first character in (string) $start or (string) $end is ‘-‘, the last occuring string will be used.
*
* If $ignore_case is true, substrpos will not care about the case.
* If $ignore_case is false (or anything that is not (boolean) true, the function will be case sensitive.
* Both of the above: only applies if either $start or $end are strings.
*
* echo substrpos(‘This is a string with 0123456789 numbers in it.’, 5, ‘5’);
* // Prints ‘is a string with 01234’;
*
* echo substrpos(‘This is a string with 0123456789 numbers in it.’, ‘5’, 5);
* // Prints ‘56789’
*
* echo substrpos(‘This is a string with 0123456789 numbers in it and two strings.’, -60, ‘-string’)
* // Prints ‘s is a string with 0123456789 numbers in it and two ‘
*
* echo substrpos(‘This is a string with 0123456789 numbers in it and two strings.’, -60, ‘-STRING’, true)
* // Prints ‘s is a string with 0123456789 numbers in it and two ‘
*
* echo substrpos(‘This is a string with 0123456789 numbers in it and two strings.’, -60, ‘-STRING’, false)
* // Prints ‘s is a string with 0123456789 numbers in it and two strings.’
*
* Warnings:
* Since $start and $end both take either a string or an integer:
* If the character or string you are searching $str for is a number, pass it as a quoted string.
* If $end is (integer) 0, an empty string will be returned.
* Since this function takes negative strings (‘-search_string’):
* If the string your using in $start or $end is a ‘-‘ or begins with a ‘-‘ escape it with a ‘\’.
* This only applies to the *first* character of $start or $end.
*/// Define stripos() if not defined (PHP < 5).
if (! is_callable ( «stripos» )) function stripos ( $str , $needle , $offset = 0 ) return strpos ( strtolower ( $str ), strtolower ( $needle ), $offset );
>
>function substrpos ( $str , $start , $end = false , $ignore_case = false ) // Use variable functions
if ( $ignore_case === true ) $strpos = ‘stripos’ ; // stripos() is included above in case it’s not defined (PHP < 5).
> else $strpos = ‘strpos’ ;
>// If end is false, set it to the length of $str
if ( $end === false ) $end = strlen ( $str );
>// If $start is a string do what’s needed to make it an integer position for substr().
if ( is_string ( $start )) // If $start begins with ‘-‘ start processing until there’s no more matches and use the last one found.
if ( $start < 0 >== ‘-‘ ) // Strip off the ‘-‘
$start = substr ( $start , 1 );
$found = false ;
$pos = 0 ;
while(( $curr_pos = $strpos ( $str , $start , $pos )) !== false ) $found = true ;
$pos = $curr_pos + 1 ;
>
if ( $found === false ) $pos = false ;
> else $pos -= 1 ;
>
> else // If $start begins with ‘\-‘, strip off the ‘\’.
if ( $start < 0 >. $start < 1 >== ‘\-‘ ) $start = substr ( $start , 1 );
>
$pos = $strpos ( $str , $start );
>
$start = $pos !== false ? $pos : 0 ;
>// Chop the string from $start to strlen($str).
$str = substr ( $str , $start );// If $end is a string, do exactly what was done to $start, above.
if ( is_string ( $end )) if ( $end < 0 >== ‘-‘ ) $end = substr ( $end , 1 );
$found = false ;
$pos = 0 ;
while(( $curr_pos = strpos ( $str , $end , $pos )) !== false ) $found = true ;
$pos = $curr_pos + 1 ;
>
if ( $found === false ) $pos = false ;
> else $pos -= 1 ;
>
> else if ( $end < 0 >. $end < 1 >== ‘\-‘ ) $end = substr ( $end , 1 );
>
$pos = $strpos ( $str , $end );
>
$end = $pos !== false ? $pos : strlen ( $str );
>// Since $str has already been chopped at $start, we can pass 0 as the new $start for substr()
return substr ( $str , 0 , $end );
>
