Parse Twitter text using PHP preg_replace - javascript

I have the following code which parses the Twitter text to change links, mentions and hashes into hyperlinks:
function parseTwitterText($text) {
$returnText = $text;
$hashPattern = '/\#([A-Za-z0-9\_]+)/i';
$mentionPattern = '/\#([A-Za-z0-9\_]+)/i';
$urlPattern = '/(http[s]?\:\/\/[^\s]+)/i';
$robotsFollow = false;
// SCAN FOR LINKS FIRST!!! Otherwise it will replace the hashes and mentions
$returnText = preg_replace($urlPattern, '\<a href\="$1" ' + (($robotsFollow)? '':'rel\=\"nofollow\"') + '\>$1\<\/a\>', $returnText);
$returnText = preg_replace($hashPattern, '\<a href\="http\:\/\/twitter\.com\/\#\!\/search\?q\=\%23$1" ' + (($robotsFollow)? '':'rel\=\"nofollow\"') + '\>\#$1\<\/a\>', $returnText);
$returnText = preg_replace($mentionPattern, '\<a href\="http\:\/\/twitter\.com\/$1" ' + (($robotsFollow)? '':'rel\=\"nofollow\"') + '\>#$1\<\/a\>', $returnText);
return $returnText;
}
However I'm just getting 0 returned if I had a tweet like #test
I based this code on a JavaScript version I had, so wondering if I've done something wrong in the preg_replace() that only worked in the JS replace()

There are 2 problems in your code:
In PHP, you concatenate strings with ., not with a +. When using +, PHP is casting the strings to an integer before adding them, which results in the 0.
In the preg_replace() calls, you do not have to escape all the characters in the second parameter. So remove all backslashes within these three lines.
You should end up with something like this:
$returnText = preg_replace($urlPattern, '<a href="$1" ' . (($robotsFollow)? '':'rel="nofollow"') . '>$1</a>', $returnText);
$returnText = preg_replace($hashPattern, '<a href="http://twitter.com/#!/search?q=%23$1" ' . (($robotsFollow)? '':'rel="nofollow"') . '>#$1</a>', $returnText);
$returnText = preg_replace($mentionPattern, '<a href="http://twitter.com/$1" ' . (($robotsFollow)? '':'rel="nofollow"') . '>#$1</a>', $returnText);

In PHP, you use . to concatenate two strings, not + as you would in JavaScript. Also, as BluePsyduck mentioned, you don't have to escape all the characters as you're currently doing.
Change the preg_replace() statements as follows:
$returnText = preg_replace($urlPattern,
'<a href="$1" ' .
(($robotsFollow)? '' : 'rel="nofollow"') .
'>$1</a>', $returnText);
$returnText = preg_replace($hashPattern,
'<a href="http://twitter.com/#!/search?q=%23$1" ' .
(($robotsFollow)? '' : 'rel="nofollow"') .
'>#$1</a>', $returnText);
$returnText = preg_replace($mentionPattern,
'<a href="http://twitter.com/$1" ' .
(($robotsFollow)? '' : 'rel="nofollow"') .
'>#$1</a>', $returnText);
Test:
header('Content-Type: text/plain');
echo parseTwitterText('#foo lala');
echo parseTwitterText('#test');
Output:
#foo lala
#test
Demo.

Related

Comma doesn't separate parameters

Trying to set up a WhatsApp button with a custom message, I've created a script in JavaScript to do that and calling it onclick.
I've tried moving quotation marks around but nothing works, this might be a silly issue but I just started with coding and can't get this to work, been trying since yesterday.
Here is my JavaScript code:
function sendSms(number, title) {
window.open('https://api.whatsapp.com/send?phone=' + number + '&text=' + 'hello' + title);
}
Here is my PHP code:
echo '<span class="ad-whatsapp" onclick="sendSms(\' '. $ad_wa .' , '. str_replace(" ", "%20", get_the_title()) . '\')"></span>';
It seems to be sending the whole content of the parenthesis as the number parameter instead of separating the 2.
function sendSms(number, title) {
window.open('https://api.whatsapp.com/send?phone=' + number + '&text=' + 'hello' + title);
}
echo '<span class="ad-whatsapp" onclick="sendSms(\' '. $ad_wa .'\' , \''. str_replace(" ", "%20", get_the_title()) . '\')">bb</span>';
Try using this JavaScript:
function sendSms(number, title) {
window.open(`https://api.whatsapp.com/send?phone=${number}&text=hello${title}`);
}
With this PHP:
<?php
$replaced = str_replace(" ", "%20", get_the_title());
echo '<span class="ad-whatsapp" onclick="sendSms(\'' . $ad_wa . '\', \'' . $replaced . '\')">SEND</span>';
?>
Good luck.
Try using this instead:
echo "<span class='ad-whatsapp' onclick=\"sendSms('".$ad_wa."' , '".str_replace(" ", "%20", $this->get_the_title())."')\">asdf</span>";

Post to php variables in javascript

In php, I want to pass a php variable using the jquery.post method.
The first figure shows the code that post the variable
first
The second figure shows to read the posted variable.second
php variable contains some statements, but output will print the variable names like "$rxss", "$sxss".
The post method seems to be writing the data part incorrectly, so please let me know how to write it.
add
i already tested
echo '<script type="text/javascript">
$(document).ready(function() {
$.post("scanner/getStatus.php", {testId:' . "$testId" . ',chkCnt:' . "$chkCount" . ',rxss:' . "$rxss" . ',sxss:' . "$sxss" . ',sqli:' . "$sqli" . ',basqli:' . "$basqli" . ',autoc:' . "$autoc" . ',idor:' . "$idor" . ',dirlist:' . "$dirlist" . ',bannerdis:' . "$bannerdis" . ',sslcert:' . "$sslcert" . ',unredir:' . "$unredir" . ',clamav:' . "$clamav" . '}, function(data){$("#status").html(data)});
var refreshId = setInterval(function() {
$.post("scanner/getStatus.php", {testId:' . "$testId" . ',chkCnt:' . "$chkCount" . ',rxss:' . "$rxss" . ',sxss:' . "$sxss" . ',sqli:' . "$sqli" . ',basqli:' . "$basqli" . ',autoc:' . "$autoc" . ',idor:' . "$idor" . ',dirlist:' . "$dirlist" . ',bannerdis:' . "$bannerdis" . ',sslcert:' . "$sslcert" . ',unredir:' . "$unredir" . ',clamav:' . "$clamav" . '}, function(data){$("#status").html(data)});
}, 500); ......
-
echo '<script type="text/javascript">
$(document).ready(function() {
$.post("scanner/getStatus.php", {testId:' . "$testId" . ',chkCnt:' . "$chkCount" . ',rxss:"" + $rxss + "",sxss:"" + $sxss + "",sqli:""+ $sqli + "",basqli:"" + $basqli + "",autoc:"" + $autoc + "",idor:"" + $idor + "",dirlist:"" + $dirlist + "",bannerdis:"" + $bannerdis + "",sslcert:"" + $sslcert + "",unredir:"" + $unredir + "",clamav:"" + $clamav + ""}, function(data){$("#status").html(data)});
var refreshId = setInterval(function() {
$.post("scanner/getStatus.php", {testId:' . "$testId" . ',chkCnt:' . "$chkCount" . ',rxss:"" + $rxss + "",sxss:"" + $sxss + "",sqli:""+ $sqli + "",basqli:"" + $basqli + "",autoc:"" + $autoc + "",idor:"" + $idor + "",dirlist:"" + $dirlist + "",bannerdis:"" + $bannerdis + "",sslcert:"" + $sslcert + "",unredir:"" + $unredir + "",clamav:"" + $clamav + ""}, function(data){$("#status").html(data)});
}, 500); ......
but when these test not showing getStatus.php and apache log haven't error
You can you this $("$yourvariable")
Also take a look at this How to call PHP function from string stored in a Variable

How to pass a string value ' String_value ' if i cant use " " and ' '?

Actually here i am passing a int value and string value by javascript:function(); ,
im little bit confuse how to send string value by using single quote ' ' because here echo is using double " " and href is using single ' ' .
echo "<td align='center'><a href='javascript:EditNotePopup($id,$ref_id,$string_value);'><i class=' icon-edit'></i></a></td>";
so,above i cannot use ' ".$srting_value." ' or \ symbol . How can i fix it and pass a string value using ' '
For Example,i am trying like this
javascript:EditPopup(1,09898,'hello_world');
so hello world is using ' '.
Thanks in advance
Escape with a backslash
echo '<td align="center"><i class=" icon-edit"></i></td>';

magento javascript:void(0) in navigation menu

I've been trying to add Javascript:void(0)to my magento website's navigation bar for a long time.
I read many articles about this subject and almost all of them says I should edit
/app/code/core/Mage/Catalog/Block/Navigation.php or copy this to local folder end edit there.
here one of the popular way that i followed;
To remove url, href functionality of the top menu categories, you can take the following steps:
Create some folder as this path: app/code/local/Mage/Catalog/Block
Copy file Navigation.php from app/code/core/Mage/Catalog/Block to
app/code/local/Mage/Catalog/Block
Go to function _renderCategoryMenuItemHtml()
Replace this code
$html[] = '<a href="'.$this->getCategoryUrl($category).'"'.$linkClass.'>';
$html[] = '<span>' . $this->escapeHtml($category->getName()) . '</span>';
$html[] = '</a>';
with this code
if($category->getLevel()== 2 && $hasActiveChildren) {
$html[] = '<a href="[removed]void(0);"'.$linkClass.'>';
$html[] = '<span>' . $this->escapeHtml($category->getName()) . '</span>';
$html[] = '</a>';
} else {
$html[] = '<a href="'.$this->getCategoryUrl($category).'"'.$linkClass.'>';
$html[] = '<span>' . $this->escapeHtml($category->getName()) . '</span>';
$html[] = '</a>';
}
But it didn't work for me. Weirdly even if i delete /app/code/core/Mage/Catalog/Block/Navigation.php the navigation menu works just fine. Were it gets the code for working I have no idea.
Maybe you have an idea that can help me. I just want to put Javascript:void(0) to the navigation menu.
I feel it's issue of cache or Magento Compiler. I suggest you to do the following steps from magento admin.
go to admin->System->Cache Management and clear/flush all the cache
go to admin->System->Tools->Compilation. Check if compilation is enabled then disabled it and clear cache again and run your compilation process
I was also looking to solve this, I think the problem is that the code you linked only works on 1.7 and not on 1.9?
The solution i came up with
copy Topmenu.php from app\code\core\Mage\Page\Block\Html to app\code\local\Mage\Page\Block\Html replace on line 131:
$html .= '<li ' . $this->_getRenderedMenuItemAttributes($child) . '>';
$html .= '<a href="' . $child->getUrl() . '" ' . $outermostClassCode . '><span>'
. $this->escapeHtml($child->getName()) . '</span></a>';
to
if ($child->hasChildren()) {
$html .= '<li ' . $this->_getRenderedMenuItemAttributes($child) . '>';
$html .= '<a href=\'javascript:void(0);\'><span>'
. $this->escapeHtml($child->getName()) . '</span></a>';
}
else{
$html .= '<li ' . $this->_getRenderedMenuItemAttributes($child) . '>';
$html .= '<a href="' . $child->getUrl() . '" ' . $outermostClassCode . '><span>'
. $this->escapeHtml($child->getName()) . '</span></a>';
}
Hope this helps.

New line in alert window with jQuery jqXHR responseText

I'm currently requesting some text via jQuery on a php page. The problem is that the new line symbols \n are displayed in the alert window, and do not get interpreted as new line. I do not escape the string at any time.
In the error: function(..) block of my jQuery request, I get the string returned by php via jqXHR.responseText, here is it's exact value :
Some fields are empty!\n$name= \n$schedule= 480;1140;480;1140;480;1140;480;1140;480;1140;480;1140;480;1140\n$free_connection= false\n$free_coffee= false\n$rating= -1\n$lat= 44.715513732021336\n$lng= 1.9775390625\n
When I do this, new lines DON'T WORK :
alert(jqXHR.responseText);
So to debug, I decided to paste the php response string (which is the previous string) directly in the alert() function, and in this case the new lines WORK :
alert("Some fields are empty!\n$name= \n$schedule= 480;1140;480;1140;480;1140;480;1140;480;1140;480;1140;480;1140\n$free_connection= false\n$free_coffee= false\n$rating= -1\n$lat= 44.715513732021336\n$lng= 1.9775390625\n)");
The string is exactly the same, but yet new lines don't work when I use jqXHR to get it.
Anybody has any clue ?
EDIT: php code that generates the string :
$errorMessage = 'Some fields are empty!' . '\n'
. '$name= ' . $name . '\n'
. '$schedule= ' . $schedule . '\n'
. '$free_connection= ' . $free_connection . '\n'
. '$free_coffee= ' . $free_coffee . '\n'
. '$rating= ' . $rating . '\n'
. '$lat= ' . $lat . '\n'
. '$lng= ' . $lng . '\n';
echo $errorMessage;
You're using the wrong type of quotes. In PHP, escape sequences aren't processed in single quotes, only in double quotes. So it should be:
$errorMessage = 'Some fields are empty!' . "\n"
. '$name= ' . $name . "\n"
. '$schedule= ' . $schedule . "\n"
. '$free_connection= ' . $free_connection . "\n"
. '$free_coffee= ' . $free_coffee . "\n"
. '$rating= ' . $rating . "\n"
. '$lat= ' . $lat . "\n"
. '$lng= ' . $lng . "\n";
echo $errorMessage;
I do not know if I understood well but You can try
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
or
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});

Categories

Resources