How to check if URL contains certain words? - php

I want to show custom content if current URL contain certain words.
So far, I'm able to achieve this if the URL contains just the word, 'cart', using the code below. However, I want to be able to check for other words like 'blog', 'event' and 'news'. How do I go about this.
<?php $path = $_SERVER['REQUEST_URI'];
$find = 'cart';
$pos = strpos($path, $find);
if ($pos !== false && strstr($_SERVER['HTTP_REFERER'], 'path/to/site') !== false) :
?>
Custom content
<?php else: ?>

Use an array but use preg_grep instead. IMO it's the correct preg_ function for this use case.
preg_grep — Return array entries that match the pattern
//www.example.com?foo[]=somewords&foo[]=shopping+cart
//for testing
$_GET['foo'] = ['somewords', 'shopping cart'];
$foo = empty($_GET['foo']) ? [] : $_GET['foo'];
$words = ['cart','foo','bar'];
$words = array_map(function($item){
return preg_quote($item,'/');
},$words);
$array = preg_grep('/\b('.implode('|', $words).')\b/', $foo);
print_r($array);
Output
Array
(
[1] => shopping cart
)
Sandbox

Use an Array and loop through it .. IE
<?php $path = $_SERVER['REQUEST_URI'];
$arr = array();
$arr[0] = 'cart';
$arr[1] = 'foo';
$arr[2] = 'bar';
foreach($arr as $find){
$pos = strpos($path, $find);
if ($pos !== false && strstr($_SERVER['HTTP_REFERER'], 'path/to/site') !== false){
echo "custom content";
break; // To exit the loop if custom content is found -- Prevents it showing twice or more
}
}

There are several solutions such as preg_match_all():
Code
<?php $path = $_SERVER['REQUEST_URI'];
$find = '/(curt|blog|event|news)/i';
$number_of_words_in_my_path = preg_match_all($find, $path);
if ($number_of_words_in_my_path > 0 && strstr($_SERVER['HTTP_REFERER'], 'path/to/site') !== false) :
?>
Custom content
<?php else: ?>

Related

if repeating response in foreach in while loop

I have an if in a foreach in a while loop. I'm searching for a string in another string of text.
$base = 'someurl';
$url = $base;
while(1){
$json = json_decode(file_get_contents($url));
$more = $json->next_page;
$next = $json->next_page_number;
if($more){
$url = $base.'&page='.$next;
}else{
break;
}
foreach($json as $data){
$c = $data->text; // search in
$s = 'string';
$t = 'prefix1'.$s; // search for
$m = 'prefix2'.$s; // search for
if( (strpos($c, $t) || strpos($c, $m)) !== false ){
echo '<p>hello, i found one or more ($t and/or $m) of the search criteria in the text string $c .</p>';
break;
}
}
}
The problem is that I get the echo from the if statement twice :(
What I want to achieve is to only make the echo happen ONCE, if $t and/or $m is present in $c.
Well, i guess you're receiving the echo twice because you found 2 records that match your condition, is that possible?
If so, and you only want to check that your condition matches at least once on the array, you could break the foreach after you found your first match, like:
if( ( strpos( $c, $t ) || strpos( $c, $m ) ) !== false ){
echo '<p>hello, I was told I was true</p>';
break;
}
OK, so found a working solution for my particular problem (although I'm still not clear as to why the if statements response got echoed twice?).
Using preg_match instead of strpos gave me a working solution :)
if(preg_match('('.$t.'|'.$m.')', $c) === 1){
// tis' the truth echoed thru eternity
}

Clean link on search filter php

I have a function to clean a link when I filter my search results
function cleanLink($url,$remove){
$aQ = explode("&",str_replace("?", "", $url));
foreach ($aQ as $part) {
$pos = strpos($part, $remove);
if ($pos === false)
$queryClean[] = $part;
}
$line = implode("&", $queryClean);
return "?".$line;
}
$linkACTUAL = "".$_SERVER["QUERY_STRING"];
cleanLink($linkACTUAL, "q=");
echo $linkACTUAL."&q=".$word;
This works fine, for example if my url is
www.mysite.com/?q=wordx
I want to add an "order alphabetic desc" so my url returns
www.mysite.com/?q=wordx&order=desc
but if my query string is empty (e.g. www.mysite.com/) the return is
www.mysite.com/?&q=word
How can I remove the & if the query string is empty?
Change
if ($pos === false)
to
if ($pos === false && $part)
to omit empty $part string (will evaluate as false). You also should initialize $queryClean
$queryClean = array();
You can use parse_str and http_build_str to remove a parameter from the query string. You just to make sure pecl_http >= 0.23.0 is installed
function cleanLink($queryString, $remove)
{
parse_str($queryString, $query);
if (array_key_exists($remove, $query)) {
unset($query[$remove]);
}
return http_build_str($query);
}
$linkACTUAL = $_SERVER["QUERY_STRING"];
cleanLink($linkACTUAL, "q");
echo $linkACTUAL . "&q=" . $word;
For more information see http://php.net/manual/en/function.http-build-str.php and http://php.net/manual/de/function.parse-str.php
If your function is running fine when there are query string then you can simply put your function call inside if statement like
if(!empty($_GET))
{
$linkACTUAL = "".$_SERVER["QUERY_STRING"];
cleanLink($linkACTUAL, "q=");
echo $linkACTUAL."&q=".$word;
}
Updated:
echo (false === strpos($linkACTUAL, "&")) ? $linkACTUAL."q=".$word : $linkACTUAL."&q=".$word;

Php get value from text file

I have this textfile:
foo: bar
el: macho
bing: bong
cake color: blue berry
mayo: ello
And I what I'm trying to accomplish is that if I "look" for foo, it returns bar (if I look for bing, it should return bong). A way a tried to accomplish this is first search though the file, return the line with the result, put it in a string and remove everything before the ":" and display the string.
// What to look for
$search = 'bing';
// Read from file
$lines = file('file.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false)
echo $line;
$new_str = substr($line, ($pos = strpos($line, ',')) !== false ? $pos + 1 : 0);
}
echo "<br>";
echo "bing should return bong:";
echo $new_str;
But it doesn't work. Up here is just one of the many things I've tried.
Sources:
Many stackoverflow links on and comparable searches:
https://www.google.com/search?client=opera&q=php+remove+everything+after
https://www.google.com/search?client=opera&q=php+search+text+file+return+line
I've asked a question before, but the answers are to "professional" for me, I really need a noob-proof solution/answer. I've been trying to figure it out all day but I just can't get this to work.
Edit:
It's solved! Thank you so much for your time & help, I hope this might be useful to someone else to!
This should work with what you are looking for, I tested it on my server and it seems to fit what you are looking for.
$lines_array = file("file.txt");
$search_string = "bing";
foreach($lines_array as $line) {
if(strpos($line, $search_string) !== false) {
list(, $new_str) = explode(":", $line);
// If you don't want the space before the word bong, uncomment the following line.
//$new_str = trim($new_str);
}
}
echo $new_str;
?>
I would do it this way:
foreach($lines as $line)
{
// explode the line into an array
$values = explode(':',$line);
// trim the whitspace from the value
if(trim($values[1]) == $search)
{
echo "found value for ".$search.": ".$values[1];
// exit the foreach if we found the needle
break;
}
}
$search = 'bing';
// Read from file
$lines = file('text.txt');
$linea='';
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false) {
$liner=explode(': ',$line);
$linea.= $liner[1];
}
}
echo 'Search returned: '. $linea;
Explanation: - $linea var is created before loop, and it will contain search result. If value is found on line - explode string, and make array, get second var from array, put it in search results container variable.
As your data is almost YAML [see lint], you could use a parser in order to get the associated PHP array.
But if can go with your solution as well:
// What to look for
$search = 'bing';
// Read from file
$lines = file('file.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false){
echo array_pop(explode(":", $line));
}
}
Use fgetcsv:
$bits = array();
if (($handle = fopen('t.txt','r')) !== FALSE) {
while (($data = fgetcsv($handle, 0, ":")) !== FALSE) {
$bits[$data[0]] = $data[1];
}
}
# Now, you search
echo $bits['foo'];
$bits will have a key for each split part, which makes your ultimate goal quite simple. Here is what it looks like:
Array
(
[foo] => bar
[el] => macho
[bing] => bong
[cake color] => blue berry
[mayo] => ello
)

get string piece, before last needle

Given
$str = "asd/fgh/jkl/123
If we want to get string piece after last slash , we can use function strrchr() right?
In php not function, to get string piece, before last slah, that is asd/fgh/jkl ?
I know this can make via regex or other way, I am asking about internal function?
You can use
$str = "asd/fgh/jkl/123";
echo substr($str, 0,strrpos($str, '/'));
Output
asd/fgh/jkl
$str = "asd/fgh/jkl/123";
$lastPiece = end(explode("/", $str));
echo $lastPiece;
output: 123;
explode() converts the string into an array using "/" as a separator (you can pick the separator)
end() returns the last item of the array
You can do this by:
explode — Split a string by string (Documentation)
$pieces = explode("/", $str );
example
$str = "asd/fgh/jkl/123";
$pieces = explode("/", $str );
print_r($pieces);
$count= count($pieces);
echo $pieces[$count-1]; //or
echo end($pieces);
Codepad
Use this powerful custom function
/* $position = false and $sub = false show result of before first occurance of $needle */
/* $position = true and $sub false show result of before last occurance of $needle */
/* $position = false and $sub = true show result of after first occurance of $needle */
/* $position = true and $sub true show result of after last occurance of $needle */
function CustomStrStr($str,$needle,$position = false,$sub = false)
{
$Isneedle = strpos($str,$needle);
if ($Isneedle === false)
return false;
$needlePos =0;
$return;
if ( $position === false )
$needlePos = strpos($str,$needle);
else
$needlePos = strrpos($str,$needle);
if ($sub === false)
$return = substr($str,0,$needlePos);
else
$return = substr($str,$needlePos+strlen($needle));
return $return;
}

Finding tags in query string with regular expression

I have to set some routing rules in my php application, and they should be in the form
/%var/something/else/%another_var
In other words i beed a regex that returns me every URI piece marked by the % character, String marked by % represent var names so they can be almost every string.
another example:
from /%lang/module/controller/action/%var_1
i want the regex to extract lang and var_1
i tried something like
/.*%(.*)[\/$]/
but it doesn't work.....
Seeing as it's routing rules, and you may need all the pieces at some point, you could also split the string the classical way:
$path_exploded = explode("/", $path);
foreach ($path_exploded as $fragment) if ($fragment[0] == "%")
echo "Found $fragment";
$str='/%var/something/else/%another_var';
$s = explode("/",$str);
$whatiwant = preg_grep("/^%/",$s);
print_r($whatiwant);
I don’t see the need to slow down your script with a regex … trim() and explode() do everything you need:
function extract_url_vars($url)
{
if ( FALSE === strpos($url, '%') )
{
return $url;
}
$found = array();
$parts = explode('/%', trim($url, '/') );
foreach ( $parts as $part )
{
$tmp = explode('/', $part);
$found[] = ltrim( array_shift($tmp), '%');
}
return $found;
}
// Test
print_r( extract_url_vars('/%lang/module/controller/action/%var_1') );
// Result:
Array
(
[0] => lang
[1] => var_1
)
You can use:
$str = '/%lang/module/controller/action/%var_1';
if(preg_match('#/%(.*?)/[^%]*%(.*?)$#',$str,$matches)) {
echo "$matches[1] $matches[2]\n"; // prints lang var_1
}

Categories