The right way to do preg_match and preg_replace [duplicate] - php

This question already has answers here:
PHP: Best way to check if input is a valid number?
(6 answers)
Closed 2 years ago.
So I have been trying to bring back to life my very old website.
I started with replacing ereg with preg, but it's been a very long time since I have written any PHP.
At the moment I am stuck on this:
$_POST['amount'] = preg_replace("/[^0-9/]",'',$_POST['amount']);
$_POST['amount'] = round($_POST['amount']);
if (!preg_match('/[^0-9]/', $_POST['amount'])) {
echo "Invalid amount.";
}else {
echo "Passed";
}
I'm not entirely sure where I am going wrong. Should it be !preg_match or preg_match for example?
Edit:
$_POST['amount'] allows a user to enter a number and needs to replace anything else other than a number if attempted.

Not sure what the error is (i.e. what is the current output and what was expected). However, one mistake in the prompt is that the pattern for the first preg_replace appears to have a typo: /[^0-9/] should probably be /[^0-9]/
preg_replace("/[^0-9]/",'',$_POST['amount']);
The rest looks like correct syntax (i.e. preg_match returns 0 if there is no match).

Related

How would I take a string, find a certain character, add a character, and continue until end of string? [duplicate]

This question already has answers here:
PHP: Variables in a Postgresql Query
(2 answers)
Closed 3 years ago.
I’m working on a project where I need to use postgresql to update info. I need to take
Martin’s chik ‘n’ chips
And make change it to
Martin\’s chik \’n\’ chips
How would I do this? I’ve looked at other posts, and found out to use substr() to create the new string and strpos() to find the ‘s, and even setting a new variable to keep the position of the previous ‘
Edit: thanks everyone, clearly didn’t do enough research!
If in PHP:
Check out str_replace(). e.g.
$text = "Martin’s chik ‘n’ chips";
$apostrophe = array("'","`","‘","’");
$newtext = str_replace($apostrophe,"\'",$text);
In this specific example, if you don't have any of the 'fancy' apostrophes, check out addslashes() as this will solve everything for you

php strpos does not detect # hashtag character [duplicate]

This question already has answers here:
Simple PHP strpos function not working, why?
(5 answers)
Closed 3 years ago.
Using php 7.1 and I have strange issue with strpos(). We have post value that needs to detect presence of # sign.
Tried:
if(strpos($_POST["text"],"#")>0)
{..} else {..}
and
if(strpos($_POST["text"],"#")!== false)
{..} else {..}
but it always go to else part. Also tried escaping hashtag
if(strpos($_POST["text"],"\#")>0)
Any idea what to do?
Hashtag is first value and I need to know is it present. Example value is:
$_POST["text"]='# 1010';
if(strpos($_POST["text"],"#")!== false)
should be used, not:
if(strpos($_POST["text"],"#")>0)
# could be the first character which is not >0.

Do-While loop not stopping on request [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 4 years ago.
I've been learning PHP for over a year now and it's always the little things that seem to go disastrously wrong, or I just forget what I'm doing.
I've been using Do-While loops in a few projects but recently one I created just didn't work. Once I numbed it down to almost nothing I noticed it just isn't stopping according to user input.
do {
echo "Hi there\n";
echo "Echo\n";
$userInput = readline();
} while ($userInput = 'continue');
echo "Exit";
I don't understand what's going wrong but something is. From my understanding the program will echo twice, listen for the user's input and loop through again while the user types continue - if not then will echo Exit. What am I doing wrong? This is such a simple task and it's annoying me. All the other topics I've searched for don't seem to be helping.
You need to use
while ($userInput == 'continue');
instead of
while ($userInput = 'continue');
because you have used wrong operator (= [assign] instead of == [equals])

Eregi and preg_match replacement, big error on capcha and email validator [duplicate]

This question already has answers here:
How can I convert ereg expressions to preg in PHP?
(4 answers)
Closed 3 years ago.
I know there are a lot of questions related to this subject, but after some days of research I didn't find something that could help this particular case, so here it is:
I have replaced the deprecated eregi with preg_match in 2 files of my website, and now the capcha code gives an error on the registration page, even if the code is absolutely correct
On the registration page I have replaced this
function is_valid_username($username) {
if(!eregi("^[a-z0-9]*$", trim(str_replace(" ","",$username)))) {
return 0;
}
with this
if(!preg_match("^[a-z0-9]*$^", trim(str_replace(" ","",$username)))) {
return 0;
}
And in my second file I have replaced this:
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email)) {
$result = 0;
}
with this
if(!preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$^", $email)) {
$result = 0;
}
How can I resolve this issue?
eregi is case-insensitive, so you would need to add the i modifier to the end of your preg_match expression.
Also, ^ denotes the start of the input and you have used it as the delimiter.
So this should be more like the original:
#^[a-z0-9]*$#i
and
#^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$#i
By the way, I don't know what your captcha code requires exactly, but there are easier ways to verify an email address using filter_var().

PHP Regular expression - forget everything after? [duplicate]

This question already has answers here:
Beautiful way to remove GET-variables with PHP?
(12 answers)
How to remove content from url after question mark. preg_match or preg_replace?
(2 answers)
Closed 8 years ago.
I have this url: http:www.blabla.com/x/x/x/x?username=testuser
I need a string to read this url, but forget everything and including the ? mark.
So it becomes this: http:www.blabla.com/x/x/x/x
The reason for this is because I am making this variable:
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
And this code:
if($host == "http:www.blabla.com/x/x/x/x") {
echo "lul";
}
But right now, the URL changes depending on what user is on, and it has to execute the echo no matter what user is on.
So I read some reges and preg_match etc. and I just wanted to hear your opinions or advice. How would I accomblish this the best? thanks!
This is too trivial of a task for regex.
$host = $_SERVER['SERVER_NAME'] . explode("?", $_SERVER['REQUEST_URI'], 2)[0];
(Note: this assumes you're up-to-date, or at least using PHP 5.4, for the dereference to work without a temporary variable)
Or if you must omit the get / request section just explode ? and use $host[0]

Categories