Check if a string conains a specific word [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I need to check if an URL address contains some text. so I created this code.
function url_mapping_name( $urlname ) {
if (str_contains($urlname, 'amazon.de')) {
echo "amazon;
}
if (str_contains($urlname, 'brickset')) {
echo 'brickset';
} else {
echo 'no URL';
}
I am trying to say.
Look for "amazon.de" in $urlname, if the URL contains amazon.de return amazon, if the URL contains brickset.com return brickset, if nothing found return no URL
But something is wrong and I do know where I did a mistake
Thanks for helping me.

The line
echo 'amazon';
is missing a quotation mark. Note the color coding changes. That is usually caused by a missing quotation mark.
Assuming by "return" you mean having the function assign that value to a variable, all the output strings should be
return 'string';
instead of
echo 'string';
A potential additional issue is having 2 if statements instead of using else if. If you do intent to echo the strings instead of returning them, it should be like this so when it's equal to 'amazon' it doesn't also echo 'no url'
function url_mapping_name( $urlname ) {
if (str_contains($urlname, 'amazon')) {
echo 'amazon';
} else if (str_contains($urlname, 'brickset')) {
echo 'brickset';
} else {
echo 'no URL';
}

Thanks for the help, I used the following improvements and it works now.
I fixed the closing quote
replaced echo with return
used elseif - it returned "amazonno URL" before as #aynber wrote
function url_mapping_name( $urlname ) {
if (str_contains($urlname, 'amazon.de')) {
return 'amazon';
}
elseif (str_contains($urlname, 'brickset')) {
return 'brickset';
} else {
return 'no URL';
}
}
Thank you very much for helping me.

Related

How to convert a global script into a function? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hi guys i'm having a small issue when i try and convert my exisiting script into a simple function. I'll leave my code below.
PHP:
function service_check($postcode) {
$op_postcodes = array(... "DG10","DG3","DG4" ...);
if(isset(htmlentities($postcode))) {
$postcode_checker = trim(strtoupper(htmlentities($postcode)));
$trim_postcode = trim(substr(htmlentities($postcode_checker, 0, -3)));
if(empty($postcode_checker)) {
$error = "We require your postcode to check our service in your area.";
} else if(!valid_postcode($postcode_checker)) {
$otp = "The postcode you entered is invalid.";
} else if(!in_array($trim_postcode, $op_postcodes)) {
$otp = "Sorry, but we don't provide our service's in your area, just yet.";
} else {
$otp = "Great news! We're in your area and you are eligible to order our services!";
$_SESSION['customer_postcode'] = $postcode_checker;
}
} else {
$otp = "To get started please enter your postcode.";
}
}
My current usage of the function is <?php service_check($_POST['service_check']); ?>
My error is:
Fatal error: Cannot use isset() on the result of a function call (you can use "null !== func()" instead) in /home/domain.com/public_html/controller/application/functions/locale.SM.php on line 27
change this
if(isset(htmlentities($postcode))) {
to this
$pc = htmlentities($postcode);
if(isset($pc)) {
read this if you get sometime - http://php.net/manual/en/function.isset.php http://php.net/manual/en/function.htmlentities.php
Since your questions wasn't complete i assume so now an edit. The better approach could be to use !empty() instead of isset() on our if condition.
Even better, reove htmlentities method call from your if block and then later use html entities when you actually need it.

Php Loop While Condition = True [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a php file which basically reads a page using JSON and a variable is returned to it (pending/paid/expired). now my simple requirement is if the returned variable is paid/expired the respective actions for them should be taken and the loop should not be repeated but if the response is pending the code should recheck after 10 seconds. A similar cycle then happens again and so on till the loop is stopped(by receiving either a expired/paid response.
here is the code i prepared for it using the examples i found at various places but this doesnt seem to work correctly.. pls guide..
while($end==0) {
$json = file_get_contents('http://old.kbourbaki.com/xlisteningpageprestashop.aspx?yyyyyyy');
$obj = json_decode($json);
$result=$obj->response;
echo($result);
if ($result=='paid') {
p('Order Successfull');
$end=1;
} elseif ($result=='expired' ) {
p('status = expired');
$end=1;//ex
} else {
d('status = Pending');
sleep(10);
}
}
CODE UPDATED extra '{' removed
You have one too many curly braces.
The proper elseif and else block should look like this
} elseif ($result=='expired' ) {
p('status = expired');
$end=1;//ex
} else {
It would help you a lot if you properly formatted your code.
You close the IF condition before the last ELSE just delete the closing clasp.
if($result=='paid'){
p('Order Successfull');
$end=1;
}else if($result=='expired'){
p('status = expired');
$end=1;//ex
}else{
d('status = Pending');
sleep(10);
}

Should conditions go inside or outside of function/method [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
What is preferable: A function that decides itself if it should do anything, or deciding whether to call that function?
function x() {
if ($userIsLoggedIn) {
alwaysHelloUser();
}
if ($visitorRegion != 'US') {
alwaysDisplayNoInternationalShipping();
}
if ($day == 'Sunday') {
alwaysLockDownStore();
}
}
function alwaysLockDownStore() {
//close store
//offer alternative store
//show opening hours
//display form for user leaving order for next day
exit("Sorry, we are closed!");
}
or
function y() {
perhapsSayHelloUser($user);
maybeDisplayNoInternationalShipping($region);
sometimesLockDownStore($day);
}
function sometimesLockDownStore($day) {
if ($day == 'Sunday') {
//close store
//offer alternative store
//show opening hours
//display form for user leaving order for next day
exit ("Sorry, we are closed!");
}
}
The example is trivial, but imagine enabling functions using configuration or access rights. Is there an accepted standard? My gut tells me to go for y() when there is something like exit() involved, breaking the normal flow. Otherwise, encapsulation and DRY would favor x(). What do you think?
Edit I've expended the example. My question is really: If there is a condition on which a function/method should be executed, should that control take place in the function (tidy but outcome is uncertain) or outside it (calling is verbose, but expected output is always the same)?
I'd prefer to keep the main functionality in the function. Extra logic outside. Because the function will do just that what is intented. Or you would everytime run the function needed or not. Depending how complex your problem will be.
function lockStoreOnDay($day) {
// do locking
return "Sorry, we are closed on $day!";
}
echo lockStoreOnDay('Sunday'); //will print "Sorry, we are closed on Sunday!"
echo lockStoreOnDay('Saturday'); //will print "Sorry, we are closed on Saturday!"
Generally: Why not use a Class?
If you have access rights or a configuration this information could be stored in an Array or Object. So you iterate through the Array or search for your keyword and than process whatever should be processed. I. e. make a function call.
function lockStoreOnDay()
{
//do locking
return "Sorry, we are closed!";
}
$config_closeOnDay = array (
'Sunday'
);
foreach ($config_closeOnDay as $dayToCloseOn) {
echo lockStoreOnDay();
}
Maybe this helps.
You shouldn't have such constraints hardcoded inside function. You should aim for something like:
function isStoreLocked($dayToCheck, $daysLocked)
{
// You can replace "locking" logic with database or something
// There shouldn't be an raw array of days inside code
return in_array($dayToCheck, $daysLocked);
}
Then in your code:
$curentDayName = date('l');
$lockedDays = array('Saturday', 'Sunday');
if(isStoreLocked($currentDayName, $daysLocked))
{
die('Sorry, store is locked!');
}
To give context to my answer: if you do it using a framework (my choice is Symfony2) isStoreLocked should be a service or a repository method and it should be called inside controller while returning Response (rather than simple die()).

Syntax error - unexpected ":" [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
My php script directs to a url depending on which submit button was pressed. However, when I run the test I'm getting an error saying line 4 contains an unexpected ":" but my line 4 is my header script with the url?
I'm confused because I have other scripts similar to this and they don't give me that error. Can anyone tell me what I'm missing, might be simple, I have been caught being simple before.
<?php
if ($_REQUEST['Dish1'] == 'Dish1')
{
header(“Location: http://blahblah”.urlencode($_POST[‘uid’]));
}
else if ($_REQUEST['Dish1'] == 'Dish2')
{
header(“Location: http://blahblah2”.urlencode($_POST[‘uid’]));
}
else if ($_REQUEST['Dish1'] == 'Dish3')
{
header(“Location: http://blahblah3”.urlencode($_POST[‘uid’]));
}
etc.....
?>
You are using curly quotes.
Replace all the “ ” and ‘ ’ to " and ' respectively.
You are using the wrong quotes... use "" instead of “”. Refer to Wikipedia, you must use typewriter quotes, not curly or inverted commas.
PD: Also PHP Parse error: syntax error, unexpected '.' on line 15 ; )
Replace you code with following
<?php
if ($_REQUEST['Dish1'] == 'Dish1')
{
header("Location: http://blahblah.urlencode".($_POST['uid']));
}
else if ($_REQUEST['Dish1'] == 'Dish2')
{
header("Location: http://blahblah2".urlencode($_POST['uid']));
}
else if ($_REQUEST['Dish1'] == 'Dish3')
{
header("Location: http://blahblah3".urlencode($_POST['uid']));
}
?>
Is it not much easier to write:
$lookup = array('Dish1' = > 'http://blba1', 'Dish2' = > 'http://blba2');
if( isset($lookup[$_REQUEST['Dish1']]))
header("Location: " . $lookup[$_REQUEST['Dish1']]);

preg_match multiple expressions

hi guys i was wondering how could i build e regExp that says:
"this string may contain 1-25 letters that are not these specific words:"root","bin","download","shutdown"
So I thought:
$dang_words="/(root)|(bin)|(shutdown)|(download)/";
$reg_exp="/^[a-z]{1,25}$/";
if(preg_match($reg_exp,$field) || !preg_match($dang_words,$field))
{
echo "your input it's okkk!";
}
else
echo "this is a bad word!!";
But it's not working
why?
thanks
Luca
$dangerous_words="/(root)|(bin)|(shutdown)|(download)/";
$reg_exp="/^[a-z]{1,25}$/";
if(preg_match($reg_exp,strtolower(trim($field))) && !preg_match($dangerous_words,strtolower(trim($field))))
{
echo "your input it's okkk!";
}
else
echo "this is a bad word!!";
You have your logical operators messed up.. Just changed from || to &&.
Close... Try this:
/^(?!.*(root|bin|shutdown|download))[a-z]{1,25}$/
It uses a forward assertion
So, it becomes:
if (preg_match('/^(?!.*(root|bin|shutdown|download))[a-z]{1,25}$/', $content)) {
echo "Your input is ok";
} else {
echo "there is a bad word/invalid content";
}
I think your issue lies with all the ( ). In some old code I created a while ago I used this:
$stopInjectionVerbs = "/(alter|begin|cast|convert|create|cursor|declare|delete|drop|end|exec|fetch|insert|kill|open|select|sys|table|update)/";
$errors = array();
if (preg_match($stopInjectionVerbs, $select)) {
$errors[] = "Can not use SQL injection Strings";
}
This all works correctly. Have a go without the brackets around each individual word.

Categories