find "/p" with preg_match in first place of string - php

Small problem:
$content='/p test some text';
when "/p" is in front of the line the string should be exploded to an array
if(preg_match('^(/p)',$content)==true) {
$private=explode(" ",$content,3);
}
i think their is an error, but i've no idea for the correct search parameter

This should work for you:
(No need to compare it with true, because if it doesn't find anything it returns an empty array, which then is false. Also you need delimiters for your regex and escape the slash with a backslash)
$content='/p test some text';
if(preg_match('/^\/p/',$content)) {
//^ ^ See delimiters
$private=explode(" ",$content,3);
}

Why not a simple test
if ($content{0} == '/' && $content{1} == 'p' ) {
$private=explode(" ",$content,3);
}

Related

How to disable ' - ; : ~ ` from input and remove from string?

I tried to add extra security by removing special characters. I want to allow letters, numbers and ? = & only.
I tried:
if (strpos($_SERVER['REQUEST_URI'],'\'')) { echo 'true'; }
I cannot just simply put ' in between the '' as it breaks it so I tried adding the \ but it didn't work.
Is there a way to detect all the symbols in the url string or input field?
EDIT:
tried adding < simply into the list
if (preg_match('#[#*,!$\'\-;:<>~`^|\(\\)\\{\\}\\[\\]]#i', $_SERVER['REQUEST_URI']) || strpos($_SERVER['REQUEST_URI'],'script')) {
echo 'Cannot do that';
}
I tried adding ([\<])([^\>]{1,})*([\>]) into there but it didn't work.
I also tried adding a condition if strcmp($_SERVER['REQUEST_URI'], strip_tags($_SERVER['REQUEST_URI'])) != 0
and when i added into the url, it didn't do anything
Use preg_match to test for anything but the characters you want:
if (preg_match('#[^a-z0-9?=&]#i', $str)) { echo 'true'; }
Use preg_replace to remove them:
$str = preg_replace('#[^a-z0-9?=&]#i', '', $str);
If you just want to prohibit certain characters, use a regular expression that just matches those characters:
if (preg_match('#[\'\-;:~`]#i', $str)) { echo 'true'; }
You can fix that using double quotes as strings delimiter, try this
if (strpos($_SERVER['REQUEST_URI'],"'")) { echo 'true'; }
One thing that none of the posts addressed is why strpos didn't work for you. strpos can return two types. It can return an integer that is greater than or equal to zero. 0 being the first character. It can also return a boolean type false. To check if if strpos found a match it would have to have been written like this:
if (strpos($_SERVER['REQUEST_URI'],'\'') !== false) { echo 'true'; }
From the PHP Documentation The comparison $a !== $b operator works this way:
return TRUE if $a is not equal to $b, or they are not of the same type.
Information on strpos returning two types (boolean false or an integer) can be found in this PHP strpos Documentation. In particular:
Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
So as you can see 0 and false are not the same thing which is why your test failed.
As for security and strings in PHP I recommend you look at this StackOverflow article for some opinions on the matter.

Checking to see if a string contains any characters

I would like to check and see if a given string contains any characters or if it is just all white space. How can I do this?
I have tried:
$search_term= " ";
if (preg_match('/ /',$search_term)) {
// do this
}
But this affects search terms like this as well:
$search_term= "Mark Zuckerburg";
I only want a condition that checks for all white space and with no characters.
Thanks!
ctype_space does this.
$search_term = " ";
if (ctype_space($search_term)) {
// do this
}
The reason your regular expression doesn’t work is that it’s not anchored anywhere, so it searches everywhere. The right regular expression would probably be ^\s+$.
The difference between ctype_space and trim is that ctype_space returns false for an empty string. Use whatever’s appropriate. (Or ctype_space($search_term) || $search_term === ''…)
Use trim():
if(trim($search_term) == ''){
//empty or white space only string
echo 'Search term is empty';
}
trim() will cut whitespace from both start and end of a string - so if the string contains only whitespace trimming it will return empty string.

Str replace and logical

I want to replace { by {{} and } by {}}, because, I need to escape those { & } with {}.
if I've as input {blah} I want my script to output {{}blah{}}, see?
But it is not working look at what I did
$output = str_replace(array("}", "{"), array("{}}", "{{}"), '{blah}');
But as output I got this : {{}blah{{}}} instead of {{}blah{}}
PHP iterates the whole string for each array item you put in the $search parameter.
It is in fact replacing '{blah}' into '{blah{}}' with your first array item '{', and then from that into '{{}blah{{}}}' because there is another '{' after the first replacement.
You better off doing this with regular expression, with a single RegExp pattern it will run only once in your input string.
$str = preg_replace('/(\{|\})/', '{\\1}', '{blah}');
That's because the replacement itself contains the string to search for. I would rewrite it with preg_replace_callback instead:
echo preg_replace_callback('/{|}/', function($match) {
return $match[0] == '{' ? '{{}' : '{}}';
}, '{bla}');
// {{}bla{}}

Using PHP's preg_match to see if a value matches a list of values

I want to see if a variable contains a value that matches one of a few values in a hard-coded list. I was using the following, but recently found that it has a flaw somewhere:
if (preg_match("/^(init)|(published)$/",$status)) {
echo 'found';
} else {
echo 'nope';
}
I find that if the variable $status contains the word "unpublished" there is still a match even though 'unpublished' is not in the list, supposedly because the word 'unpublished' contains the word 'published', but I thought the ^ and $ in the regular expression are supposed to force a match of the whole word. Any ideas what I'm doing wrong?
Modify your pattern:
$pattern = "/^(init|published)$/";
$contain = "unpublished";
echo preg_match($pattern, $contain) ? 'found' : 'nope' ;
This pattern says our string must be /^init$/ or /^published$/, meaning those particular strings from start to finish. So substrings cannot be matched under these constraints.
In this case, regex are not the right tool to use.
Just put the words you want your candidate to be checked against in an array:
$list = array('init', 'published');
and then check:
if (in_array($status, $list)) { ... }
^ matches the beginning of a string. $ matches the end of a string.
However, regexes are not a magic bullet that need to get used at every opportunity.
In this case, the code you want is
if ( $status == 'init' || $status == 'published' )
If you are checking against a list of values, create an array based on those values and then check to see if the key exists in the array.

PHP Regular Expression Failing

My current regular expression should be correct, though I wouldn't expect so, it doesn't work properly. It won't return "Got Match"
My currrent code is as follows:
$id = "http://steamcommunity.com/id/TestID";
if (preg_match("^http://steamcommunity\.com/id/.*?\n$", $id)) {
print "Got match!\n";
}
You're missing delimiters on your regex:
if (preg_match("#^http://steamcommunity\.com/id/.*?\n$#", $id)) {
^--here ^--here
Note that I've used # as the delimiter here, since that saves you having to escape all of the internal / charrs, if you'd used the traditional / as the delimiter.
You need a delimiter, like this:
if (preg_match("#^http://steamcommunity\.com/id/.*?$#", $id)) {
^ ^
And what's with the newline at the end? Surely you don't need that.
You're missing delimiters. For example:
"#^http://steamcommunity\.com/id/.*?\n$#"
Also, you're trying to match a newline (\n) that isn't in your string.
You need to add the pattern delimiter:
$id = "http://steamcommunity.com/id/TestID";
if (preg_match("#^http://steamcommunity\.com/id/.*?(\n|$)#", $id)) {
print "Got match!\n";
}
There are a couple of things that are wrong with it. First of all, you need to delimit the start and end of your regex with a character. I used #. You're also matching for a new line at the end of your regex, which you don't have and likely won't ever have in your string.
<?php
$id = "http://steamcommunity.com/id/TestID";
if (preg_match("#^http://steamcommunity\.com/id/.*?$#", $id)) {
print "Got match!\n";
}
?>
http://codepad.viper-7.com/L7XctT
First of all, your regex shouldn't even compile because it's missing delimiters.
if (preg_match("~^http://steamcommunity\.com/id/.*?\n$~", $id)) {
^---- these guys here -----^
Second of all, why do you have a \n if your string doesn't contain a new line?
And finally, why are you using regex at all? Effectively, you are just trying to match a constant string. This should be equivalent to what you are trying to match:
if (strpos($id, 'http://steamcommunity.com/id/') === 0) {
You need to have starting and ending delimiter in your pattern like /pattern/ or #pattern# or with brackets (pattern). Why is that? To have some pattern modifiers after ending delimiter like #pattern#i (ignore case)
preg_match('(^http://steamcommunity\.com/id/.*?\n$)', $id)
As the say your patten is start and end wrong. (Delimiter)
But this will be a better match of a 64-bit Steam ID. (Minimum 17 and Maximum 25 numbers)
if( preg_match("#^http://steamcommunity\.com/id/([0-9]{17,25})#i", $id, $matches) )
{
echo "Got match! - ".$matches;
}
I believe that there is no need for you to require that the string must end with a line break.
Explanation.
http://steamcommunity\.com/id/([0-9]{17,25})
^--- string ---^^-- Regexp --^
[0-9] - Match a number between 0 to 9
{17,25} - Make 17 to 25 matches
() - Returns match
Or use pattern as those (It is the same):
/^http:\/\/steamcommunity\.com\/id\/([0-9]{17,25})/i
(^http://steamcommunity\.com/id/([0-9]{17,25}))i
Regular Expressions PHP Tutorial
Online regular expression testing <- Dont use delimiter.
<?php
# URL that generated this code:
# http://txt2re.com/index-php.php3?s=http://steamcommunity.com/id&-1
$txt='http://steamcommunity.com/id';
$re1='(http:\\/\\/steamcommunity\\.com\\/id)'; # HTTP URL 1
if ($c=preg_match_all ("/".$re1."/is", $txt, $matches))
{
$httpurl1=$matches[1][0];
print "($httpurl1) \n";
}
#-----
# Paste the code into a new php file. Then in Unix:
# $ php x.php
#-----
?>
Resorces:
http://txt2re.com/index.php3?s=http://steamcommunity.com/id&-1

Categories