Php if value like

PHP Like вещь, похожая на MySQL Like, для оператора if?

Причина, по которой я задаю этот вопрос, заключается в том, что я не хочу изменять команду MySQL, это длинная страница с множеством вещей на ней, я не хочу создавать для этого другую функцию.

Дайте мне знать, возможно ли это, если возможно, то как это сделать.

11 ответов

if ($ something похоже на% $ somethingother%)

Является ли это возможным?

Я не хочу менять команду MySQL, это длинная страница, на которой много всего.

Используйте какой-нибудь хороший редактор, который поддерживает регулярные выражения в поиске и замене, и превратите его во что-то вроде:

if(stripos($something, $somethingother) !== FALSE)

Я знаю, это не актуальный вопрос, но я решил аналогичную проблему 🙂

/** * SQL Like operator in PHP. * Returns TRUE if match else FALSE. * @param string $pattern * @param string $subject * @return bool */ function like_match($pattern, $subject) < $pattern = str_replace('%', '.*', preg_quote($pattern, '/')); return (bool) preg_match("/^$/i", $subject); > 
like_match('%uc%','Lucy'); //TRUE like_match('%cy', 'Lucy'); //TRUE like_match('lu%', 'Lucy'); //TRUE like_match('%lu', 'Lucy'); //FALSE like_match('cy%', 'Lucy'); //FALSE 

Мне это нравится — мелочь. Линия шаблона должна быть $pattern = str_replace(‘%’, ‘.*’, preg_quote($pattern,’/’)); . В противном случае для preg_match () не будет экранироваться косая черта.

Используйте функцию, эту строку поиска в другой строке, например: strstr , strpos , substr_count .

Strpos () не работает, поэтому я должен использовать этот preg_match ()

$a = 'How are you?'; if (preg_match('/\bare\b/', $a))

Как в этом примере, я подбираю слово «являются» надеюсь для кого-то это будет полезно

Но вам нужно будет указать строку в нижнем регистре, тогда она будет работать нормально. Пример функции strstr:

$myString = "Hello, world!"; echo strstr( $myString, "wor" ); // Displays 'world!' echo ( strstr( $myString, "xyz" ) ? "Yes" : "No" ); // Displays 'No' 

Используйте эту функцию, которая работает так же, как оператор SQL LIKE , но возвращает логическое значение, и вы можете создать свое собственное условие с еще одним оператором if.

function like($str, $searchTerm) < $searchTerm = strtolower($searchTerm); $str = strtolower($str); $pos = strpos($str, $searchTerm); if ($pos === false) return false; else return true; >$found = like('Apple', 'app'); //returns true $notFound = like('Apple', 'lep'); //returns false if($found) < // This will execute only when the text is like the desired string >

Если у вас есть доступ к серверу MySQL, отправьте такой запрос с MySQLi:

$SQL="select case when '$Value' like '$Pattern' then 'True' else 'False' end as Result"; $Result=$MySQLi->query($SQL)->fetch_all(MYSQLI_ASSOC)[0]['Result']; 

Результатом будет строка, содержащая True или False. Позвольте PHP делать то, для чего он нужен, и использовать SQL для лайков.

Я думаю, что он или она ищет только аналогичный синтаксис или трюк в PHP, чтобы сделать то же самое, что и ключевое слово sql ‘like’, но я не уверен, что он / она использует для этого базу данных.

Может быть, у кого-то нет доступа к SQL-серверу, но возникает вопрос. Если вы не используете SQL, зачем вам пытаться имитировать функцию SQL в PHP? В PHP нет ничего подобного. В нем есть регулярное выражение, что лучше, если вы знаете, как его использовать, но есть загвоздка.

Недавно я столкнулся с этим требованием и придумал следующее:

/** * Removes the diacritical marks from a string. * * Diacritical marks: * * @param string $string The string from which to strip the diacritical marks. * @return string Stripped string. */ function stripDiacriticalMarks(string $string): string < return preg_replace('/[\x-\x]/u', '', \Normalizer::normalize($string , \Normalizer::FORM_KD)); > /** * Checks if the string $haystack is like $needle, $needle can contain '%' and '_' * characters which will behave as if used in a SQL LIKE condition. Character escaping * is supported with '\'. * * @param string $haystack The string to check if it is like $needle. * @param string $needle The string used to check if $haystack is like it. * @param bool $ai Whether to check likeness in an accent-insensitive manner. * @param bool $ci Whether to check likeness in a case-insensitive manner. * @return bool True if $haystack is like $needle, otherwise, false. */ function like(string $haystack, string $needle, bool $ai = true, bool $ci = true): bool < if ($ai) < $haystack = stripDiacriticalMarks($haystack); $needle = stripDiacriticalMarks($needle); >$needle = preg_quote($needle, '/'); $tokens = []; $needleLength = strlen($needle); for ($i = 0; $i < $needleLength;) < if ($needle[$i] === '\\') < $i += 2; if ($i < $needleLength) < if ($needle[$i] === '\\') < $tokens[] = '\\\\'; $i += 2; >else < $tokens[] = $needle[$i]; ++$i; >> else < $tokens[] = '\\\\'; >> else < switch ($needle[$i]) < case '_': $tokens[] = '.'; break; case '%': $tokens[] = '.*'; break; default: $tokens[] = $needle[$i]; break; >++$i; > > return preg_match('/^' . implode($tokens) . '$/u' . ($ci ? 'i' : ''), $haystack) === 1; > /** * Escapes a string in a way that `UString::like` will match it as-is, thus '%' and '_' * would match a literal '%' and '_' respectively (and not behave as in a SQL LIKE * condition). * * @param string $str The string to escape. * @return string The escaped string. */ function escapeLike(string $str): string < return strtr($str, ['\\' =>'\\\\', '%' => '\%', '_' => '\_']); > 

Приведенный выше код поддерживает Unicode, чтобы улавливать такие случаи, как:

like('Hello 🙃', 'Hello _'); // true like('Hello 🙃', '_e%o__'); // true like('asdfas \\🙃H\\\\%🙃É\\l\\_🙃\\l\\o asdfasf', '%' . escapeLike('\\🙃h\\\\%🙃e\\l\\_🙃\\l\\o') . '%'); // true 

Вы можете попробовать все это на https://3v4l.org/O9LX0.

Я думаю, стоит упомянуть функцию str_contains() , доступную в PHP 8 , которая выполняет проверку с учетом регистра, указывающую, содержится ли строка в другой строке, возвращая истину или ложь.

Пример взят из документации:

$string = 'The lazy fox jumped over the fence'; if (str_contains($string, 'lazy')) < echo "The string 'lazy' was found in the string\n"; >if (str_contains($string, 'Lazy')) < echo 'The string "Lazy" was found in the string'; >else < echo '"Lazy" was not found because the case does not match'; >//The above will output: //The string 'lazy' was found in the string //"Lazy" was not found because the case does not match 

Пример like_match () — лучший, этот SQL-запрос ведьмы прост (я использовал его раньше), но работает медленно, а затем ресурсы сервера базы данных like_match () и exost, когда вы выполняете итерацию по ключам массива и каждый раунд удаляет сервер базы данных с запросом, обычно не требуется . Я сделал это быстрее, используя элементы шаблона для вырезания / сжатия массива, но регулярное выражение для массива работает всегда быстрее. Мне нравится like_match () 🙂

Источник

PHP if

Summary: in this tutorial, you’ll learn about the PHP if statement and how to use it to execute a code block conditionally.

Introduction to the PHP if statement

The if statement allows you to execute a statement if an expression evaluates to true . The following shows the syntax of the if statement:

 if ( expression ) statement;Code language: HTML, XML (xml)

In this syntax, PHP evaluates the expression first. If the expression evaluates to true , PHP executes the statement . In case the expression evaluates to false , PHP ignores the statement .

The following flowchart illustrates how the if statement works:

PHP if flowchart

The following example uses the if statement to display a message if the $is_admin variable sets to true :

 $is_admin = true; if ($is_admin) echo 'Welcome, admin!';Code language: HTML, XML (xml)

Since $is_admin is true , the script outputs the following message:

Curly braces

If you want to execute multiple statements in the if block, you can use curly braces to group multiple statements like this:

 if ( expression ) < statement1; statement2; // more statement >Code language: HTML, XML (xml)

The following example uses the if statement that executes multiple statements:

 $can_edit = false; $is_admin = true; if ( $is_admin ) < echo 'Welcome, admin!'; $can_edit = true; >Code language: HTML, XML (xml)

In this example, the if statement displays a message and sets the $can_edit variable to true if the $is_admin variable is true .

It’s a good practice to always use curly braces with the if statement even though it has a single statement to execute like this:

 if ( expression ) Code language: HTML, XML (xml)

In addition, you can use spaces between the expression and curly braces to make the code more readable.

Nesting if statements

It’s possible to nest an if statement inside another if statement as follows:

 if ( expression1 ) < // do something if( expression2 ) < // do other things > >Code language: HTML, XML (xml)

The following example shows how to nest an if statement in another if statement:

 $is_admin = true; $can_approve = true; if ($is_admin) < echo 'Welcome, admin!'; if ($can_approve) < echo 'Please approve the pending items'; > >Code language: HTML, XML (xml)

Embed if statement in HTML

To embed an if statement in an HTML document, you can use the above syntax. However, PHP provides a better syntax that allows you to mix the if statement with HTML nicely:

 if ( expession) : ?>  endif; ?>Code language: HTML, XML (xml)

The following example uses the if statement that shows the edit link if the $is_admin is true :

html> html lang="en"> head> meta charset="UTF-8"> title>PHP if Statement Demo title> head> body>  $is_admin = true; ?>  if ( $is_admin ) : ?> a href="#">Edit a>  endif; ?> a href="#">View a> body> html>Code language: HTML, XML (xml)

Since the $is_admin is true , the script shows the Edit link. If you change the value of the $is_admin to false , you won’t see the Edit link in the output.

A common mistake with the PHP if statement

A common mistake that you may have is to use the wrong operator in the if statement. For example:

 $checked = 'on'; if( $checked = 'off' ) < echo 'The checkbox has not been checked'; >Code language: HTML, XML (xml)

This script shows a message if the $checke d is ‘off’ . However, the expression in the if statement is an assignment, not a comparison:

$checked = 'off'Code language: PHP (php)

This expression assigns the literal string ‘off’ to the $checked variable and returns that variable. It doesn’t compare the value of the $checked variable with the ‘off’ value. Therefore, the expression always evaluates to true , which is not correct.

To avoid this error, you can place the value first before the comparison operator and the variable after the comparison operator like this:

 $checked = 'on'; if('off' == $checked ) < echo 'The checkbox has not been checked'; >Code language: HTML, XML (xml)

If you accidentally use the assignment operator (=), PHP will raise a syntax error instead:

 $checked = 'on'; if ('off' = $checked) < echo 'The checkbox has not been checked'; >Code language: HTML, XML (xml)
Parse error: syntax error, unexpected '=' . Code language: JavaScript (javascript)

Summary

  • The if statement executes a statement if a condition evaluates to true .
  • Always use curly braces even if you have a single statement to execute in the if statement. It makes the code more obvious.
  • Do use the pattern if ( value == $variable_name ) <> to avoid possible mistakes.

Источник

PHP One Line If Statement

Decision-making is a critical part of any productive application. Conditional statements allow us to evaluate matching conditions and take action accordingly.

In PHP, decision-making constructs are implemented using if and if…else statements. Let us discuss using these statements and implement them in our programs.

PHP If Statement

The if statement in PHP allows you to check for a specific condition and perform a particular action if the state is true or false.

The syntax is shown below:

The program checks the condition in parenthesis. If the condition is true, it executes the code inside the curly braces.

We can illustrate this with an example as shown below:

The previous code checks if the value stored by the $age variable is greater than 18. If true, it prints the string “pass!!”.

The output is shown below:

PHP If…Else

In the previous example, we check for one condition and act if it is true. However, if the condition is false, the program does not do anything.

We can use an if…else block to specify the action if the condition is false.

The following syntax is provided:

The following example is shown:

In this example, we set the value of the $age variable to 10. Then, we use an if..else block to check if the age is greater than 18. If true, echo “Pass!!” else print “Denied!!”.

The previous code should return output as shown below:

PHP If…Elseif…Else

The other condition constructs in PHP is the if..elseif..else statement. This allows you to evaluate multiple conditions in a single block.

The following syntax is shown:

if ( test condition 1 ) {
// action if condition 1 is true
} elseif ( test condition 2 ) {
// action if condition 2 is true
} else {
// action if all are false
}

We can implement the following example:

If we run the previous code, we should get the following output:

PHP One Line If Statement

PHP provides us with a ternary operator to create a one-line if statement. It acts as a more concise version of an if…else statement.

The syntax is provided below:

Here’s the following example :

Both the ternary operator and an if…else statements work similarly. However, one is more verbose and readable, while the other is minimal and concise.

Conclusion

This tutorial covered conditional statements in PHP, including the ternary operator statement.

In addition, examples were provided to evaluate the matching conditions. Check other Linux Hint articles for more tips and tutorials.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list

Источник

Читайте также:  JavaScript Alert Box by PHP
Оцените статью