I have a header that basically says something like this:
"
Forum
A great place for support.
"
And I need it to display on certain pages of my site, the ones related to the forum.
However on other pages I might want a header like:
"
Donate
Help keep us online.
"
The adresses on the forum part of the site would be similar to these.
http://localhost/index.php?p=/discussions
http://localhost/index.php?p=/activity
http://localhost/index.php?p=/discussion/6/oh-dear#Item_1
And the donate one might be like this:
http://localhost/index.php?p=/plugin/page/donate
So I need some way to have a script that goes
if url has (discussions, activity, discussion)
then use this header
"<b>Forum<b> <br> a great place for support
if else url has (donate)
then use this header
"<b>Donate<b> <br> help keep us online
else
use this header
"<b>Website<b> <br> this is our website
Use the Javascript location object:
url = location.href;
if (url.indexOf('discussions') && url.indexOf('activity') && url.indexOf('discussion')) {
document.getElementById('parent').appendChild(child-element);
else if (url.indexOf('donate')) {
document.getElementById('parent').appendChild(other-child-element);
}
else {
document.getElementById('parent').appendChild(another-child-element);
}
A function like this might help.
And if you don't know how to get variable from url, use $_GET['p']
function contains($substring, $string) {
$pos = strpos($string, $substring);
if($pos === false) {
// string needle NOT found in haystack
return false;
}
else {
// string needle found in haystack
return true;
}
}
Another (more elegant) serverside solution for you... If your URL's are always appearing with the "path" in the p parameter, you could utilize PHP's explode() and in_array() functions to make your code a little more easy to handle. Take this URL for example -
http://localhost/index.php?p=/plugin/page/donate
If we execute an explode() function on the $_GET['p'] variable, we'll get an array like this -
Array(
'plugin',
'page',
'donate'
)
Now you can execute an in_array() function to see if the string you are looking for exists in this array -
if (in_array('form',explode($_GET['p']){
// we are in the forum!
}
References -
in_array()
explode()
If you would like to do this serverside, you could always use PHP's strpos() function. It will return the location of a string within another. So all you would have to do is examine the $_SERVER['query_string'] variable and execute an strpos() search -
if (strpos($_SERVER['QUERY_STRING'],'forum')) >= 0){
// forum appears in the query string!
}
The strpos() function returns the index of the string you are searching, so remember that 0 is a valid index. When strpos() does not find a match. it will return false.
Here what I'm doing is examining one of the $_SERVER variable, they contain all sorts of information about the server and what it's current parameters are. One of these is the query string - that's all the text that comes after the ? in the URL. Once I have that, the strpos() function will search for something in that value.
Related
I have one array which contains multiple strings. I have another array which contain also strings but they are shorter. My goal is to check is there any partial match in the bigger array for every item from the smaller array. However preg_match doesnt work at all with variables. If I put raw input everything seems fine but otherwise results is false. I have tried almost every possible regex combination but without success. Sample code:
//Lets say $needle is 3333 and bigPatern has 10 records with 10 digits each, for example third record is 5125433331. I want to perform the partial match and get true
$needle = $smlPattern[0]; //debugging with first item from smaller array
$needle2 = "/$needle/"; // I tried [$needle], ^..&, to concatenate and etc
foreach ($bigPatern as $val)
{
if (preg_match($needle2, $val))
{
echo "YES";
}
}
Any tips what Im doing wrong?
Please escape your regex input!
$needle2 = "/".preg_quote($needle,'/')."/"; //
Don't blindly add user input to your regex, much for the same reason you need to escape user input in SQL queries. In regex, the biggest issue is usually the ReDoS problem, where a malicious user can create a specially crafted regex that will use hours, or more, to execute, stealing all the CPU from your server.
Main wrong thing in your example is to use regexp for checking the presence of a string. There is a strpos function for that.
if ( strpos($bigOne, $smallOne) !== false ) {
echo "bigOne contains smallOne";
}
You can even use strpos function to achieve the same purpose. It finds the position of the first occurrence of a substring in a string, and returns false if no match is found.
$needle = $smlPattern[0];
$needle2 = "needle";
foreach ($bigPatern as $val){
if (strpos($val, $needle2) !== false){
echo "YES";
}
}
I have a string like
"subscription link :%list:subscription%
unsubscription link :%list:unsubscription%
------- etc"
AND
I have an array like
$variables['list']['subscription']='example.com/sub';
$variables['list']['unsubscription']='example.com/unsub';
----------etc.
I need to replace %list:subscription% with $variables['list']['subscription'],And so on
here list is first index and subscription is the second index from $variable
.Is possible to use eval() for this? I don't have any idea to do this,please help me
Str replace should work for most cases:
foreach($variables as $key_l1 => $value_l1)
foreach($value_l1 as $key_l2 => $value_l2)
$string = str_replace('%'.$key_l1.':'.$key_l2.'%', $value_l2, $string);
Eval forks a new PHP process which is resource intensive -- so unless you've got some serious work cut out for eval it's going to slow you down.
Besides the speed issue, evals can also be exploited if the origin of the code comes from the public users.
You could write the string to a file, enclosing the string in a function definition within the file, and give the file a .php extension.
Then you include the php file in your current module and call the function which will return the array.
I would use regular expression and do it like that:
$stringWithLinks = "";
$variables = array();
// your link pattern, in this case
// the i in the end makes it case insensitive
$pattern = '/%([a-z]+):([a-z]+)%/i';
$matches = array();
// http://cz2.php.net/manual/en/function.preg-replace-callback.php
$stringWithReplacedMarkers = preg_replace_callback(
$pattern,
function($mathces) {
// important fact: $matches[0] contains the whole matched string
return $variables[$mathces[1]][$mathces[2]];
},
$stringWithLinks);
You can obviously write the pattern right inside, I simply want to make it clearer. Check PHP manual for more regular expression possibilities. The method I used is here:
http://cz2.php.net/manual/en/function.preg-replace-callback.php
I am trying to work out a script to log IPs from poll votes on a message board, that will only be fired off if a vote is cast in one of our polls. Edit: I'm doing this via a web beacon, because I don't have access to the poll's programming. /edit
When the script fires off, it needs to know which poll is being voted in, since there are often multiple polls that are open at the same time, and log the IP of voters in a flat file that is dedicated to that poll.
First, I grab the referring URL, which is formatted like this:
http://subdomain.sample.com/t12345,action=vote
If 'vote' is found in the referring URL, the next thing I want to do is grab that t# and turn it into a variable, so I can log info in a file named t12345.txt or 12345.txt, either-or doesn't really matter, as long as it matches the topic number of the poll.
The numbers after the /t are the only thing that should change in this URL. There are currently 5 digits here, and I don't expect this to change any time soon.
My question is: How do I grab this t# from the URL and create a variable from it?
Thank you in advance!
Check out preg_match
preg_match('|/t[0-9]{5}|', $url, $matches);
if (count($matches)) {
$t_number = $matches[0]; // "/t12345"
$number = substr($t_number, 2, strlen($t_number)); // 12345
}
Assumptions:
1) The referring url will never have the pattern t#####. (t12345.com/vote)
2) You will always have five digits. (if this changes, you can do {5,6} to match 5-6 instances
Curtis already answered, but here's a non-regex alternative:
Use parse_url on the URL to get the "path".
Use explode with a comma delimiter to get your t# as array element 0 in the result.
(optional) Use explode on element 1 of the result from 2 with a delimiter of = to get "action" in element 0 and "vote" in element 1 of this new result.
Eg.
$url = "http://subdomain.sample.com/t12345,action=vote";
$url_pieces = parse_url($url);
$path = str_replace("/","",$url_pieces["path"]);
$args = explode(',',$path);
t_number_thingy = $args[0];
Edit: added str_replace as parse_url will include slash on the path.
Non regex solution (don't know about performance) and there is probably a better way but it works.
<?php
$var = "http://subdomain.sample.com/t12345,action=vote;";
$remove = "http://subdomain.sample.com/t";
$intCount = 5;
echo substr($var, strpos($var, $remove) + strlen($remove), $intCount);
?>
phpFiddle
You dont need to use regex on this you can also use str_replace(); and basename();
Like:
<?php
$ref = "http://subdomain.sample.com/t12345,action=vote";
if(substr($ref,-4)==="vote"){
$ref = basename(str_replace(',action=vote','',$ref));
}
echo $ref; //t12345
?>
Or a one liner:
$ref = (substr($ref,-4)==="vote") ? basename(str_replace(',action=vote','',$ref)) : "Unknown";
I need some help with strpos().
Need to build a way to match any URL that contains /apple-touch but also need to keep specifics matching, such as "/favicon.gif" etc
At the moment, the matches are listed out individually as part of an array:
<?php
$errorurl = $_SERVER['REQUEST_URI'];
$blacklist = array("/favicon.gif", "/favicon.png", "/apple-touch-icon-precomposed.png", "/apple-touch-icon.png", "/apple-touch-icon-72x72-precomposed.png", "/apple-touch-icon-72x72.png", "/apple-touch-icon-114x114-precomposed.png", "/apple-touch-icon-114x114.png", "/apple-touch-icon-57x57-precomposed.png", "/apple-touch-icon-57x57.png", "/crossdomain.xml");
if (in_array($errorurl, $blacklist)) { // do nothing }
else { // send an email about error }
?>
Any ideas?
Many thanks for help
Instead of a regex, you could also remove all occurrences of your blacklist items with str_replace and compare the new string to the old one:
if ( str_replace($blacklist, '', $errorurl) !== $errorurl )
{
// do nothing
}
else
{
// send an email about error
}
If you want to use regex for this, and you want a single regex string that will capture all the values in your existing blacklist plus match any apple-touch string, then something like this would do it.
if(preg_match('/^\/(favicon|crossdomain|apple-touch.*)\.(gif|png|xml)$/',$_SERVER['REQUEST_URI']) {
//matched the blacklist!
}
To be honest, though, that's far more complex than you need.
I'd say you'd be better off keeping the specific values like favicon.gif etc in the blacklist array you already have; it'd make it a lot easier when you come to adding more items to the list.
I'd only consider using regex for the apple-touch values, since you want to block any variant of them. But even with that, it would likely be simpler if you used strpos().
I have a variable like this:
33,100,200
I need to detect if it contains a specific number, say
if(var contains '33'){
do stuff
}
But it has to not work if say they didn't have 333 in the variable the above statement shouldn't validate the if statement.
Edit: This is a string not an array.
Either explode & in_array route, or preg_match('/(?<![0-9])33(?![0-9])/',$string) route, I prefer the first.
I dont quite understand the second part of your question, but this may be the code you're looking for:
if(strpos($var, '33') !== false) {
// do stuff
}
Edit Oh, now I think i get what you're looking for
if(in_array('33', explode(',', $var)) {
// do stuff
}