Php if page contains

str_contains

Выполняет проверку с учётом регистра, указывающую, содержится ли needle в haystack .

Список параметров

Подстрока для поиска в haystack .

Возвращаемые значения

Возвращает true , если needle содержится в haystack , false в противном случае.

Примеры

Пример #1 Пример использования пустой строки »

if ( str_contains ( ‘абв’ , » )) echo «Проверка существования пустой строки всегда возвращает true» ;
>
?>

Результат выполнения данного примера:

Проверка существования пустой строки всегда возвращает true

Пример #2 Демонстрация чувствительности к регистру

$string = ‘ленивая лиса перепрыгнула через забор’ ;

if ( str_contains ( $string , ‘ленивая’ )) echo «Строка ‘ленивая’ найдена в проверяемой строке\n» ;
>

if ( str_contains ( $string , ‘Ленивая’ )) echo ‘Строка «Ленивая» найдена в проверяемой строке’ ;
> else echo ‘»Ленивая» не найдена потому что регистр не совпадает’ ;
>

Результат выполнения данного примера:

Строка 'ленивая' найдена в проверяемой строке "Ленивая" не найдена потому что регистр не совпадает

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • str_ends_with() — Проверяет, заканчивается ли строка заданной подстрокой
  • str_starts_with() — Проверяет, начинается ли строка с заданной подстроки
  • stripos() — Возвращает позицию первого вхождения подстроки без учёта регистра
  • strrpos() — Возвращает позицию последнего вхождения подстроки в строке
  • strripos() — Возвращает позицию последнего вхождения подстроки без учёта регистра
  • strstr() — Находит первое вхождение подстроки
  • strpbrk() — Ищет в строке любой символ из заданного набора
  • substr() — Возвращает подстроку
  • preg_match() — Выполняет проверку на соответствие регулярному выражению

User Contributed Notes 7 notes

For earlier versions of PHP, you can polyfill the str_contains function using the following snippet:

// based on original work from the PHP Laravel framework
if (! function_exists ( ‘str_contains’ )) function str_contains ( $haystack , $needle ) return $needle !== » && mb_strpos ( $haystack , $needle ) !== false ;
>
>
?>

The polyfill that based on original work from the PHP Laravel framework had a different behavior;

when the $needle is `»»` or `null`:
php8’s will return `true`;
but, laravel’str_contains will return `false`;

when php8.1, null is deprecated, You can use `$needle ?: «»`;

The code from «me at daz dot co dot uk» will not work if the word is
— at the start of the string
— at the end of the string
— at the end of a sentence (like «the ox.» or «is that an ox?»)
— in quotes
— and so on.

You should explode the string by whitespace, punctations, . and check if the resulting array contains your word OR try to test with a RegEx like this:
(^|[\s\W])+word($|[\s\W])+

Disclaimer: The RegEx may need some tweaks

private function contains(array $needles, string $type, string $haystack = NULL, string $filename = NULL) : bool <
if (empty($needles)) return FALSE;
if ($filename)
$haystack = file_get_contents($filename);

$now_what = function(string $needle) use ($haystack, $type) : array $has_needle = str_contains($haystack, $needle);
if ($type === ‘any’ && $has_needle)
return [‘done’ => TRUE, ‘return’ => TRUE];

Читайте также:  Php check if file post

foreach ($needles as $needle) $check = $now_what($needle);
if ($check[‘done’])
return $check[‘return’];
>
return TRUE;
>

function containsAny(array $needles, string $haystack = NULL, string $filename = NULL) : bool return self::contains($needles, ‘any’, $haystack, $filename);
>

function containsAll(array $needles, string $haystack = NULL, string $filename = NULL) : bool return self::contains($needles, ‘all’, $haystack, $filename);
>

// Polyfill for PHP 4 — PHP 7, safe to utilize with PHP 8

if (! function_exists ( ‘str_contains’ )) function str_contains ( string $haystack , string $needle )
return empty( $needle ) || strpos ( $haystack , $needle ) !== false ;
>
>

Until PHP 8 was released, many-a-programmer were writing our own contain() functions. Mine also handles needles with logical ORs (set to ‘||’).
Here it is.

function contains($haystack, $needle, $offset) $OR = ‘||’;
$result = false;

$ORpos = strpos($needle, $OR, 0);
if($ORpos !== false) < //ORs exist in the needle string
$needle_arr = explode($OR, $needle);
for($i=0; $i < count($needle_arr); $i++)$pos = strpos($haystack, trim($needle_arr[$i]), $offset);
if($pos !== false) $result = true;
break;
>
>
> else $pos = strpos($haystack, trim($needle), $offset);
if($pos !== false) $result = true;
>
>
return($result);
>

Call: contains(«Apple Orange Banana», «Apple || Walnut», 0);
Returns: true

Источник

Detecting if PHP page URL contains a specific string

The query is about loading only the page content without the header menu or footer if the URL includes certain criteria. Attempting to load only the page content was unsuccessful after adding code to the header.php file. To achieve this, it is recommended to use regular expressions and preg_match. A solution could involve using PHPQuery to retrieve all links that contain a specific URL on a given page.

Check if current page url contains certain words

I’m attempting to enable users to verify if their present webpage URL includes » 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 «, but the issue is that this format can continue indefinitely, and at any given moment, I may have to conceal one of the numbers.

At present, I am utilizing a system of this sort to collect the URL of the current page.

$d = explode('?', $_SERVER['REQUEST_URI'], 2); echo 'http://' . $_SERVER['HTTP_HOST'] . $d[0]; 

I’m not sure about the process of checking specific parts of the URL and redirecting it back to the index page.

Here’s my present laravel code, for reference.

if (strpos($d, '19') !== false) < header( 'Location: http://example.com' ) ; >else

Apologies for the untidy code, my objective is to find a way to display the form without using many strpos as it’s not currently echoing out.

If the page displays as «test.php?id=1» and you retrieve data from the URL, you can utilize the $_GET method to access and process the data. In my situation, I accessed the data directly through $_GET[«id»] which returned a value of 1, allowing for a direct comparison.

Fortunately, PHP has the feature inherently integrated into its system.

Php — check if current page url contains certain words, I’m trying to find a way to make it so that you can check if your current page url contains things like 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 the problem is this format could literally go on forever and at any random time I would need to make it so that one of the numbers doesn’t display.. Currently I’m using a system like this to gather the current page URL.

Читайте также:  Сервера css как добавить

Load only page content if url contains php parameter

If the URL contains ?mode=quick , I aim to solely load the page content and prevent loading of the header menu or footer.

I attempted to load only the page content by adding the code snippet at the beginning of my header.php file, but it was unsuccessful.

By inserting the given code before the final line in page.php , I successfully halted the loading of the footer.

Can the loading of the header be prevented while achieving a similar outcome?

require "pages/".$page.".php"; require_once("layouts/footer.php"); ?> 
 $page = "home"; if(isset($_GET['page'])) < if($_GET['page']=='quick')< $page = $_GET['page']; >> 

I hope it will be helpful for you

All you have to do is reverse the placement of your logic.

To resolve the issue, I made a copy of header.php and gave it a new name, header-empty.php .

I made changes to the code in the updated header file to reduce its functionality. Afterwards, I programmed it to selectively load the header only when the correct URL parameter was provided.

I had to call the function identified by get_header() as there was no way to avoid it.

PHP Check if page contains, I’m looking for a quick code/function that will detect if a page contains a certain thing. It’s for a new project I’m working on. Basically, the user will paste a simple javascript code into their pages, but I need to make sure they do. I need a code that will scan through a specific webpage url and find the code I …

If URL contains X and URL does not contain Y

If URL contains «Little_Rock_AR»

is also being registered, when

Check if the URL includes «North_Little_Rock_AR».

What would be the correct way to phrase the Little Rock code to express.

If the URL has «Little_Rock_AR» in it, but «North» is not present.

This is the code I’m currently utilizing for Little Rock.

Utilizing regular expressions is necessary. To illustrate, a pattern similar to this is recommended.

Using ~^Little_Rock_AR~ , specify URIs that start with Little_Rock_AR.

Check out this website, it can be of further assistance — http://regexpal.com.

if ( (false !== strpos($url,'little_rock_ar') && false === strpos($url,'north')) || false !== strpos($url,'north_little_rock_ar') ) < // your code >

To accomplish this task, you must utilize both regular expression and preg_match.

Something like this should work

$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; if(preg_match('/North_Little_Rock_AR/i', $url))< //whatever you want >else if(preg_match('/Little_Rock_AR/i', $url))< //whatever you want >else < //no match either >

Check if URL has certain string with PHP, Stack Overflow Public questions & answers; Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Talent Build your employer brand ; Advertising Reach developers & technologists worldwide; About the company

Utilizing PHPQuery’s PHP support syntax, I am attempting to gather all links that feature a particular URL on a designated webpage, identified as phpquery .

include_once 'phpQuery.php'; $url = 'http://www.phonearena.com/phones/manufacturer/'; $doc = phpQuery::newDocumentFile($url); $urls = $doc['a']; foreach ($urls as $url) < echo pq($url)->attr('href') . '
'; >

The aforementioned code functions properly, however, it displays all links. My intention is to solely exhibit links that consist of «/phones/manufacturer/». Despite my attempt to do so, no results were displayed.

include_once 'phpQuery.php'; $url = 'http://www.phonearena.com/phones/manufacturer/'; $doc = phpQuery::newDocumentFile($url); $urls = $doc['a']; foreach ($urls as $url) < echo pq($url)->attr('href:contains("/phones/manufacturer/")') . '
'; >

Obtain all the URLs from the mentioned website using the code given below.

 $doc = new DOMDocument(); @$doc->loadHTML(file_get_contents('http://www.phonearena.com/phones/manufacturer/')); $ahreftags = $doc->getElementsByTagName('a'); foreach ($ahreftags as $tag) < echo "
"; echo $tag->getAttribute('href'); echo "
"; > exit;

Check out this Italian guide for a quick reference, along with the documentation for jQuery.

include_once 'phpQuery.php'; $url = 'http://www.phonearena.com/phones/manufacturer/'; $doc = phpQuery::newDocumentFile($url); $urls = $doc['a[href*="/phones/manufacturer/"]']; foreach ($urls as $url) < echo pq($url)->attr('href') . '
'; >

Php: if current url contains «/demo» do something, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more

Читайте также:  Java как проверить четность числа

Источник

W-Shadow.com

Sometimes it is necessary to verify that a given page really contains a specific link. This is usually done when checking for a reciprocal link in link exchange scripts and so on.

Several things need to be considered in this situation :

  • Only actual links count. A plain-text URL should not be accepted.
  • Links inside HTML comments () are are no good.
  • Nofollow’ed links are out as well.

Here’s a PHP function that satisfies these requirements :

function contains_link($page_url, $link_url) < /* Get the page at page_url */ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $page_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_FAILONERROR, true); $html = curl_exec($ch); curl_close($ch); if(!$html) return false; /* Remove HTML comments and their contents */ $html = preg_replace('//i', '', $html); /* Extract all links */ $regexp='/(]*href\s*=\s*[\"\']?)([^\'\" >]+)([\'\"]+[^<>]*>)/i'; if (!preg_match_all($regexp, $html, $matches, PREG_SET_ORDER)) < return false; /* No links on page */ >; /* Check each link */ foreach($matches as $match) < /* Skip links that contain rel=nofollow */ if(preg_match('/rel\s*=\s*[\'\"]?nofollow[\'\"]?/i', $match[0])) continue; /* If URL = backlink_url, we've found the backlink */ if ($match[2]==$link_url) return true; >return false; > /* Usage example */ if (contains_link('http://w-shadow.com/','http://w-shadow.com/blog/')) < echo 'Reciprocal link found.'; >else < echo 'Reciprocal link not found.'; >;

… yep, another obscure topic covered, all done 😉
Now I wonder whether I should do another post like the Top 7 Things People Want To Kill to balance this out.

Related posts :

This entry was posted on Tuesday, September 25th, 2007 at 23:21 and is filed under Web Development. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Responses to “Checking If Page Contains a Link In PHP”

This is not obscure, is it 😉 Old post, but some feedback can not harme. Your script works fine, except in these situations: 1. Page with meta robots nofollow, noindex or none 2. If the remote page is restricted in the robots.txt 3. If there is not linked to the page from the main index file. Thanks for sharing.

Leave a Reply

RSS Feed

Recent Posts

Categories

Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Privacy Policy

Privacy policy
Cthulhu generated this page with 77 queries, in 3.288 seconds.

Источник

Оцените статью