简体   繁体   中英

PHP echo -> string as 0?

how would I avoid that the following :

$_SESSION['myVar']=preg_match("[^a-zA-Z]",'',$_SESSION['myVar']);

echo $_SESSION['myVar'];

displays

0

and instead it displays/outputs the var content ? preg_match gives out mixed type, but this shouldnt be the problem...

Why, is the value of the string itself not addressable with echo (by comapring its contents, it is OK )?

Formerly I had

$_SESSION['myVar']=ereg_replace("[^a-zA-Z]",'',$_SESSION['myVar']);

ant the output óf ereg_replace was correctly displayed the variable content.

PCRE in PHP need delimiters [docs] and you probably want preg_replace [docs] :

preg_replace("/[^a-zA-Z]/",'',$_SESSION['myVar']);

Assuming you had preg_replace , even then, the brackets ( [...] ) would be interpreted as delimiters and so the engine would literally try to match a-zA-Z at the beginning of the string and would not interpret the constructor as character class.

preg_match returns an int, not mixed: http://php.net/manual/en/function.preg-match.php

Use the matches parameter to get your matches.

The problem is that preg_match returns a Boolean, 1 if the pattern was matched, 0 if it didn't. preg_match simply matches occurrences, it doesn't replace them. Here's how you use preg_match:

$matched = array();
preg_match("/[^a-zA-Z]/", $_SESSION["myVar"], $matches);

print_r($matches); // All matches are in the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM