php преобразовать строку в текст

strval

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

strval — Возвращает строковое значение переменной

Описание

Возвращает строковое значение переменной. Смотрите документацию по типу string для более подробной информации о преобразовании в строку.

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

Переменная, которую необходимо преобразовать в строку.

value может быть любого скалярного типа или объектом, который реализует метод __toString(). strval() нельзя применить к массиву или объекту, которые не реализуют метод __toString().

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

Примеры

Пример #1 Пример использования strval() с магическим методом PHP __toString().

class StrValTest
<
public function __toString ()
<
return __CLASS__ ;
>
>

// Выводит ‘StrValTest’
echo strval (new StrValTest );
?>

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

User Contributed Notes 8 notes

Some notes about how this function has changed over time, with regards the following statement:

> You cannot use strval() on arrays or on objects that
> do not implement the __toString() method.

In PHP 5.3 and below, strval(array(1, 2, 3)) would return the string «Array» without any sort of error occurring.

From 5.4 and above, the return value is unchanged but you will now get a notice-level error: «Array to string conversion».

For objects that do not implement __toString(), the behaviour has varied:

PHP 4: «Object»
PHP 5 = 5.2: Catchable fatal error: Object of class X could not be converted to string

Note on use of fmod()
I used the floating point fmod() in preference to the % operator, because % converts the operands to int, corrupting values outside of the range [-2147483648, 2147483647]

I haven’t bothered with «billion» because the word means 10e9 or 10e12 depending who you ask.

The function returns ‘#’ if the argument does not represent a whole number.

The only way to convert a large float to a string is to use printf(‘%0.0f’,$float); instead of strval($float); (php 5.1.4).

// strval() will lose digits around pow(2,45);
echo pow(2,50); // 1.1258999068426E+015
echo (string)pow(2,50); // 1.1258999068426E+015
echo strval(pow(2,50)); // 1.1258999068426E+015

// full conversion
printf(‘%0.0f’,pow(2,50)); // 112589906846624
echo sprintf(‘%0.0f’,pow(2,50)); // 112589906846624

I can’t help being surprised that

evaluates to true. It’s the same with strval and single quotes.
=== avoids it.

Why does it matter? One of my suppliers, unbelievably, uses 0 to mean standard discount and 0.00 to mean no discount in their stock files.

It seems that one is being treated as an unsigned large int (32 bit), and the other as a signed large int (which has rolled over/under).

As of PHP 5.1.4 (I have not tested it in later versions), the strval function does not attempt to invoke the __toString method when it encounters an object. This simple wrapper function will handle this circumstance for you:

__toString());
else
return strval($value);
>

In complement to Tom Nicholson’s contribution, here is the french version (actually it’s possible to change the language, but you should check the syntax 😉 )

Источник

PHP: Приведение типов

Приведение типа — это преобразование значения одного типа в значение другого типа.

Есть два вида приведения типов:

Неявное приведение типа выполняется интерпретатором автоматически, без непосредственного участия программиста. Например, значение будет автоматически преобразовано, если оператор ожидает, числовые операнды:

Чтобы выполнить явное приведение, нужно указать в круглых скобках имя требуемого типа непосредственно перед приводимым значением или переменной:

Запись имени типа в круглых скобках называется оператором приведения типа. Допускаются следующие операторы приведения типов:

Приведение к целому числу

Строки преобразуются по следующим правилам:

Для других типов поведение преобразования в integer не определено. Поэтому не нужно полагаться на любое наблюдаемое поведение, так как оно может измениться без предупреждения.

Приведение к числу с плавающей точкой

Строки преобразуются по следующим правилам:

Приведение к булеву типу

Следующие значения в результате преобразования дают значение FALSE :

Приведение к строке

Булево значение TRUE преобразуется в строку «1», а значение FALSE преобразуется в «» (пустую строку):

Целое число или число с плавающей точкой преобразуется в строку, состоящую из цифр числа:

Массивы всегда преобразуются в строку «Array» :

NULL всегда преобразуется в пустую строку:

Для преобразования объекта в строку, объект должен иметь метод __toString() :

Приведение к NULL

Приведение к типу NULL не удаляет переменную и её значение, а лишь возвращает значение типа NULL :

Источник

Php преобразовать строку в текст

Casting objects to arrays is a pain. Example:

$test = new MyClass ();
echo ‘

/*
Array
(
[MyClasspriv] => priv_value
[*prot] => prot_value
[pub] => pub_value
[MyClasspriv] => second_pub_value
)
*/

?>

Yes, that looks like an array with two keys with the same name and it looks like the protected field was prepended with an asterisk. But that’s not true:

/*
MyClasspriv (13) => priv_value
0 77 121 67 108 97 115 115 0 112 114 105 118
*prot (7) => prot_value
0 42 0 112 114 111 116
pub (3) => pub_value
112 117 98
MyClasspriv (11) => second_pub_value
77 121 67 108 97 115 115 112 114 105 118
*/

?>

The char codes show that the protected keys are prepended with ‘\0*\0’ and private keys are prepended with ‘\0’.__CLASS__.’\0′ so be careful when playing around with this.

The object casting methods presented here do not take into account the class hierarchy of the class you’re trying to cast your object into.

Value of uninitialized variable of different data types.

settype($a,’bool’);
var_dump($a); //boolean false

settype($b,’string’);
var_dump($b); //string » (length=0)

settype($c,’array’);
var_dump($c); //array (size=0) empty

settype($d,’int’);
var_dump($d); //int 0

settype($e,’float’);
var_dump($e); //float 0

You REALLY must be aware what you are doing, when you cast a lot in your code. For example, you can accidentaly change FALSE to TRUE (probably not in one line, like here):

if(TRUE === (boolean) (array) (int) FALSE) <
kaboom();
>

namaroulis stated «I found it tricky to check if a posted value was an integer»; to test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric():

in response to bhsmither at gmail.com

It raises a warning because of the bad enquoted variable

It seems (unset) is pretty useless. But for people who like to make their code really compact (and probably unreadable). You can use it to use an variable and unset it on the same line:

?>

With the unset cast:

?>

Hoorah, we lost another line!

Checking for strings to be integers?
How about if a string is a float?

/* When checking for floats, we assume the possibility of no decimals needed. If you MUST require decimals (forcing the user to type 7.0 for example) replace the sequence:
1+(\.7+)?
with
1+\.4+
*/

Источник

htmlspecialchars_decode

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

htmlspecialchars_decode — Преобразует специальные HTML-сущности обратно в соответствующие символы

Описание

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

Строка, которую надо преобразовать.

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

Возвращает преобразованную строку.

Примеры

Пример #1 Пример использования функции htmlspecialchars_decode()

Результат выполнения данного примера:

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

User Contributed Notes 8 notes

The example for «htmlspecialchars_decode()» below sadly does not work for all PHP4 versions.

Quote from the PHP manual:
«get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities().»

But it does NOT! At least not for PHP version 4.4.2.
This was already reported in a bug report (http://bugs.php.net/bug.php?id=25927), but it was marked as BOGUS.

This comment now is not to report this bug again (though I really believe it is one), but to complete the example and warn people of this pitfall.

To make sure your htmlspecialchars_decode fake for PHP4 works, you should do something like this:

This should be the best way to do it.
(Reposted because the other one seems a bit slower and because those who used the code under called it htmlspecialchars_decode_php4)

that works also with ä and » and so on.
get_html_translation_table(HTML_ENTITIES) => offers more characters than HTML_SPECIALCHARS

function htmlspecialchars_decode_PHP4($uSTR)
<
return strtr($uSTR, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
>

Well, consider someone sending ‘&’ to your PHP script:

There is, unfortunately, no reliable way to determine whether HTML is escaped or not that does not come with this caveat that I know of. Rather than try and catch the case ‘I’ve already encoded this’, you are better off avoiding double-escaping by simply escaping the HTML as close to the actual output as you can muster, e.g. in the view in an MVC development structure.

If you use `htmlspecialchars()` to change things like the ampersand (&) into it’s HTML equivalent (&), you might run into a situation where you mistakenly pass the same string to the function twice, resulting in things appearing on your website like, as I call it, the ampersanded amp; «&». Clearly nobody want’s «&» on his or her web page where there is supposed to be just an ampersand. Here’s a quick and easy trick to make sure this doesn’t happen:

= «This is a string that could be passed to htmlspecialchars multiple times.» ;

?>

Now, if your dealing with text that is a mixed bag (has HTML entities and non-HTML entities) you’re on your own.

[Update of previous note, having noticed I forgot to put in quote style]

PHP4 Compatible function:

// you can do it a bunch of times, it still won’t screw you!

?>

Put it in a function. Add it to the method of some abstract data class.

For PHP4 Compatibility:

Источник

Функции для работы со строками

Для получения информации о более сложной обработке строк обратитесь к функциями Perl-совместимых регулярных выражений. Для работы с многобайтовыми кодировками посмотрите на функции по работе с многобайтовыми кодировками.

Содержание

User Contributed Notes 24 notes

In response to hackajar yahoo com,

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

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *