preg_match not redirecting properly - preg-match

I am using the following code to determine the proper redirect. The top check matches as expected and selects the proper page to load, but the second check does not return a match and I end up being redirected to the default page. I have compared the two lines until I can't see straight. They look identical in form and function, other than the obvious difference in what I am trying to match of course. What am I missing? Is there another way to accomplish my goal that might be a better choice? Thanks as always.
if (preg_match('/\Handicap Summer Foursomes/', $eventname)) {
$form = '<a class="primary" href="signup_HSF.php?eid=' . $EID . '&squads=2">Sign-up</a>';
} else if (preg_match('/\Gigantic 5/', $eventname)) {
$form = '<a class="primary" href="signup_G5.php?eid=' . $EID . '&squads=2">Sign-up</a>';
} else {
$form = '<a class="primary" href="signup.php?eid=' . $EID . '&squads=2">Sign-up</a>';
}

if (preg_match('/\Handicap Summer Foursomes/', $eventname)) {
^^
In preg, \H is "any character that is not a horizontal whitespace character". While this would match a literal H, because that's not a horiz-WS char, it's still an escape sequence you need to be aware of.
Ditto for \G in the other pattern. in preg, \G is "first matching position in subject". That's definitely not going to match.

Related

Rewrite rules in the .htaccess file

The request is simple, however, I cannot find a way to implement it. I have links like:
httр://mysite.com/index.php?lang=EN
httр://mysite.com/index.php?route=add&lang=EN
httр://mysite.com/index.php?route=view&lang=EN
and so on. What I want is to create 301 redirects so that EN could be changed to GB. For example, if a customer opens httр://mysite.com/index.php?route=add&lang=EN, he should be redirected to httр://mysite.com/index.php?route=add&lang=GB.
I have searched for this for days and have failed to find a working solution. Please help.
Does it have to be done in .htaccess? Here's a relatively simple way of doing it in PHP:
<?
if ("EN" == $_GET['lang']) {
$params = $_GET;
$params['lang'] = "GB";
$query_strings = array();
foreach ($params as $key => $value) {
$query_strings[] = $key . "=" . $value;
}
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.mysite.com?" . join($query_strings, "&");
}
Bottom line is that it may be easier to fix this problem on a level where you can isolate each query parameter and look at just the lang parameter and determine whether to do a redirect.
With regular expressions (as you would need to use in .htaccess) it's harder to isolate just the lang part. You would also need one line per language you want to redirect and maintain the list.

XQuery looking for text with 'single' quote

I can't figure out how to search for text containing single quotes using XPATHs.
For example, I've added a quote to the title of this question. The following line
$x("//*[text()='XQuery looking for text with 'single' quote']")
Returns an empty array.
However, if I try the following
$x("//*[text()=\"XQuery looking for text with 'single' quote\"]")
It does return the link for the title of the page, but I would like to be able to accept both single and double quotes in there, so I can't just tailor it for the single/double quote.
You can try it in chrome's or firebug's console on this page.
Here's a hackaround (Thanks Dimitre Novatchev) that will allow me to search for any text in xpaths, whether it contains single or double quotes. Implemented in JS, but could be easily translated to other languages
function cleanStringForXpath(str) {
var parts = str.match(/[^'"]+|['"]/g);
parts = parts.map(function(part){
if (part === "'") {
return '"\'"'; // output "'"
}
if (part === '"') {
return "'\"'"; // output '"'
}
return "'" + part + "'";
});
return "concat(" + parts.join(",") + ")";
}
If I'm looking for I'm reading "Harry Potter" I could do the following
var xpathString = cleanStringForXpath( "I'm reading \"Harry Potter\"" );
$x("//*[text()="+ xpathString +"]");
// The xpath created becomes
// //*[text()=concat('I',"'",'m reading ','"','Harry Potter','"')]
Here's a (much shorter) Java version. It's exactly the same as JavaScript, if you remove type information. Thanks to https://stackoverflow.com/users/1850609/acdcjunior
String escapedText = "concat('"+originalText.replace("'", "', \"'\", '") + "', '')";!
In XPath 2.0 and XQuery 1.0, the delimiter of a string literal can be included in the string literal by doubling it:
let $a := "He said ""I won't"""
or
let $a := 'He said "I can''t"'
The convention is borrowed from SQL.
This is an example:
/*/*[contains(., "'") and contains(., '"') ]/text()
When this XPath expression is applied on the following XML document:
<text>
<t>I'm reading "Harry Potter"</t>
<t>I am reading "Harry Potter"</t>
<t>I am reading 'Harry Potter'</t>
</text>
the wanted, correct result (a single text node) is selected:
I'm reading "Harry Potter"
Here is verification using the XPath Visualizer (A free and open source tool I created 12 years ago, that has taught XPath the fun way to thousands of people):
Your problem may be that you are not able to specify this XPath expression as string in the programming language that you are using -- this isn't an XPath problem but a problem in your knowledge of your programming language.
Additionally, if you were using XQuery, instead of XPath, as the title says, you could also use the xml entities:
"" for double and &apos; for single quotes"
they also work within single quotes
You can do this using a regular expression. For example (as ES6 code):
export function escapeXPathString(str: string): string {
str = str.replace(/'/g, `', "'", '`);
return `concat('${str}', '')`;
}
This replaces all ' in the input string by ', "'", '.
The final , '' is important because concat('string') is an error.
Well I was in the same quest, and after a moment I found that's there is no support in xpath for this, quiet disappointing! But well we can always work around it!
I wanted something simple and straight froward. What I come with is to set your own replacement for the apostrophe, kind of unique code (something you will not encounter in your xml text) , I chose //apos// for example. now you put that in both your xml text and your xpath query . (in case of xml you didn't write always we can replace with replace function of any editor). And now how we do? we search normally with this, retrieve the result, and replace back the //apos// to '.
Bellow some samples from what I was doing: (replace_special_char_xpath() is what you need to make)
function repalce_special_char_xpath($str){
$str = str_replace("//apos//","'",$str);
/*add all replacement here */
return $str;
}
function xml_lang($xml_file,$category,$word,$language){ //path can be relative or absolute
$language = str_replace("-","_",$language);// to replace - with _ to be able to use "en-us", .....
$xml = simplexml_load_file($xml_file);
$xpath_result = $xml->xpath("${category}/def[en_us = '${word}']/${language}");
$result = $xpath_result[0][0];
return repalce_special_char_xpath($result);
}
the text in xml file:
<def>
<en_us>If you don//apos//t know which server, Click here for automatic connection</en_us> <fr_fr>Si vous ne savez pas quelle serveur, Cliquez ici pour une connexion automatique</fr_fr> <ar_sa>إذا لا تعرفوا أي سرفير, إضغطوا هنا من أجل إتصال تلقائي</ar_sa>
</def>
and the call in the php file (generated html):
<span><?php echo xml_lang_body("If you don//apos//t know which server, Click here for automatic connection")?>

simple preg_match regex needed

I am trying to preg match for tags in my strings that contain #[anyNumbers:anyNumbers:anyLetters]
i am hoping to remove the #[] leaving everything inbetween as a string that i can later filter.
What would be the easiest way to accomplish this?
$str = 'Have you heard of the #[159208207468539:274:One Day without Shoes] (ODWS) campaign? ODWS is an annual initiative by #[8416861761:274:TOMS] to bring awareness around the impact a pair of shoes can have on a child's life.';
function gettag($text){
//
//$regex = "\#[([a-z0-9-:]*)\]";
//$match = preg_match("/^$regex$/", $text);
//return $match;
return preg_replace('/#\[(\d+:\d+:[a-zA-Z]+)\]/', '${1}', $text);
}
gettag($str);
returns
Have you heard of the #[159208207468539:274:One Day without Shoes]
(ODWS) campaign? ODWS is an annual initiative by 8416861761:274:TOMS
to bring awareness around the impact a pair of shoes can have on a
child's life.
<?php
$string = "#[123:456:abcZ]";
preg_match('/^#\[(([0-9]+:){2}[a-zA-Z]+)\]$/', $string, $matches);
echo $matches[1];
Using slightly modified version of your pattern, you can do this:
function gettag($text) {
return preg_replace('/#\[([ a-z0-9-:]*)\]/i', '${1}', $text);
}
If you'd like it to be even more specific, we can modify the pattern to be stricter:
function gettag($text) {
return preg_replace('/#\[(\d+:\d+:[a-zA-Z ]+)\]/', '${1}', $text);
}
See it on codepad

is there a way to get codeigniter to create a plain text page where \n char works properly?

I am trying to use vanilla forum with proxyconnect and it requires i give it a plain text file of my user's authentication cookie values in the form below. However, when i send it the only way i can get it to work is with the tags and i needs to have the \n tag.
document should be:
UniqueID=5
Name=Kyle
Email=email#email.com
I can get it to display like that with br tags but when i use \n tags they show up like this:
UniqueID=5\nName=Kyle\nEmail=email#email.com
here is the method in the controller
function get_user_info(){
if(!empty($this->user)){
printf('UniqueID=' . $this->user['userID'] . '\n');
printf('Name=' . $this->user['userFirst'] . '\n');
printf('Email=' . $this->user['userEmail'] . '\n');
}
}
Try to use use "\n" with double quotes instead. Special characters will not be expanded when they occur in single quoted strings.
Example
printf('Name=' . $this->user['userFirst'] . "\n");
Along with what rkj has suggested above, you need to output the page as plain text. To do this, add this to the beginning of your controller's function:
$this->output->set_header("Content-Type: text/plain");

Is there a Joomla function to generate the 'alias' field?

I'm writing my own component for Joomla 1.5. I'm trying to figure out how to generate an "alias" (friendly URL slug) for the content I add. In other words, if the title is "The article title", Joomla would use the-article-title by default (you can edit it if you like).
Is there a built-in Joomla function that will do this for me?
Line 123 of libraries/joomla/database/table/content.php implements JFilterOutput::stringURLSafe(). Pass in the string you want to make "alias friendly" and it will return what you need.
If you are trying to generate an alias for your created component it is very simple. Suppose you have click on save or apply button in your created component or suppose you want to make alias through your tile, then use this function:
$ailias=JFilterOutput::stringURLSafe($_POST['title']);
Now you can insert it into database.
It's simple PHP.
Here is the function from Joomla 1.5 source:
Notice, I have commented the two lines out. You can call the function like
$new_alias = stringURLSafe($your_title);
function stringURLSafe($string)
{
//remove any '-' from the string they will be used as concatonater
$str = str_replace('-', ' ', $string);
$str = str_replace('_', ' ', $string);
//$lang =& JFactory::getLanguage();
//$str = $lang->transliterate($str);
// remove any duplicate whitespace, and ensure all characters are alphanumeric
$str = preg_replace(array('/\s+/','/[^A-Za-z0-9\-]/'), array('-',''), $str);
// lowercase and trim
$str = trim(strtolower($str));
return $str;
}

Resources