How do i detect the % character in a string

... and avoid detecting all characters as if the "%" was being used as a wifld card.
I wish to run a test like if (string contains % character) then flag = "percent"
marjogAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Roger BaklundConnect With a Mentor Commented:
>> I wish to run a test like if (string contains % character) then flag = "percent"

if(strpos($string,'%')!==false) $flag = "percent";

This test does not try to detect if it is used in conjuction with a number or not, it just detedts if the is any % character present.
0
 
profyaCommented:
Try this:
if (preg_match("/^[0-9\.]{1,}(\s)*%/", "200%"))
	echo "percentage";
else
	echo "not perccentage"; 

Open in new window

0
 
landshipCommented:
profya's solution would flag ".%" or "9   %" as a percentage, also it is anchored to the beginning of the string so a percentage in the middle of the string would not be found. A fix to the regular expression to find floating numbers properly would be:
if (preg_match("/\d*(\.?\d+)+\s?%/", "200%")) // or .2% or 2.3 %
        echo "percentage";
else
        echo "not perccentage";

Open in new window

0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
landshipCommented:
Actually if someone was using the % character as a wild card in a string of numbers, perhaps for a date (200% to figure out any year 2000-2009) it would get miss-flagged as a percentage.

I could think of other ways to flag the % symbol if you give me a better idea of how your code will be used.
0
 
profyaCommented:
lanship:
Thanks for the fix., there was an error matching .%. I understood that data are textual, that's why it is possible to find something like
200  %
The author seems to me wants to parse any possible percentage, the output can be fixed in another stage. It is better than excluding it as I think.
0
 
marjogAuthor Commented:
cxr's interpretation of my needs, "detects if the is any % character present", was coorect.
Thanks to all who responded.
0
All Courses

From novice to tech pro — start learning today.