preg_replace: BB code to HTML URL - php

I have a little script here which replaces BB code with HTML code. Everything works fine but the URLs.
$bbextended = array(
"/\[URL=(.*?)\](.*?)\[\/URL\]/i" => "$2"
);
foreach($bbextended as $match=>$replacement){
$bbtext = preg_replace($match, $replacement, $bbtext);
}
Input
[URL="http://somewebsite.come/something"]Some Website Title[/URL]
Output
Some Website Title
There are double-quotes, which obviously isn't that good.
I tried
$bbextended = array(
"/\[URL=\"(.*?)\"\](.*?)\[\/URL\]/i" => "$2"
);
in the code but it didn't work. I also tried to leave out the escape sign and quotes around the $1 in the HTML code but it didn't work neither.
Any ideas?

You should use a real parser for this, such as jBB http://jbbcode.com/

When I
Set the Find string = '/\[URL="(.*?)"\](.*?)\[\/URL\]/i'
and
Set the replace string = '$2'
I get this using simple preg_replace
Some Website Title

Related

How to replace PHP code in a file having newlinse

I got some files to change by clicking a button. To go for it, i have the old string to replace, saved in database, and also the new one.
On the click button, it executes a function that is gonna find the old string in the PHP file, then gonna replace it by the new one. (Final goal is to automate the PHP edits in a web software after an update).
My problem is that it perfectly works on short strings (without newline), but as soon as there is a newline into the file, nothing happens.
This is my actual code :
$path = '/mypath/' . $item['path'];
$old_code = $item['old_code'];
$new_code = $item['new_code'];
}
$pos = strpos(file_get_contents($path), $old_code);
$file = file_get_contents($path);
$str = str_replace($old_code, $new_code, $file);
file_put_contents($path, $str);
$pos is "true" if my $old_code doesn't have any newline.
I tried to use preg_match to remove \n, but the problem is that when i'll have to push my edits on the file with file_put_contents, every newline will also disapear.
Example of non-working str_replace :
echo "ok"; echo 'hey there is some spaces before'
echo 'this is a sentence';
$menu = ['test1', 'test200'];
print_r($menu);
$url = "/link/to/test";
$div = "echo \"<div class='central_container' align='center'>\";";
Do you have any idea for resolving this ?
Thanks
if I`m not wrong str_replace() work only with single lines . Its have 2 options.
Option line replace str_replace() with preg_replace() or just use https://regex101.com/ there also have code generator after you finish you Regex

How to add missing http:// to an anchor in a string - PHP

I wrote a code which adds hyperlink to all plain text where it finds http:// or https://. The code works pretty well for https://www.google.com and http://yahoo.com. It converts these text into clickable hyperlink with correct address.
<?php
function convert_text_to_link($str)
{
$pattern = "/(?:(https?):\/\/([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])/i";
return preg_replace($pattern, "<a href='$0' target='_blank'>$0</a>", $str);
}
$str = "https://www.google.com is the biggest search engine. It's competitors are http://yahoo.com and www.bing.com.";
echo convert_text_to_link($str);
?>
But when my code sees www.bing.com, though it adds hyperlink to it but the href attribute also becomes www.bing.com. There is no http:// prepended it. Therefore the link becomes unusable without the link http://localhost/myproject/www.bing.com will go nowhere.
How can I add http:// to www.bing.com so that it should become http://www.bing.com?
Here is your function. Try this.
function convert_text_to_link($str) {
$pattern = '#(http)?(s)?(://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])#';
return preg_replace($pattern, '$0', $str);
}
You should try and check if this works:
window.location = window.location.href.replace(/^www./, 'https:');
might be you will get your solution.
I just got to know about some other approaches too, you can try them out as per your code and requirements:
1.
str_replace("www.","http://","$str");
The test here is case-sensitive. This means that if the string is initially this will change it to http://Http://example.com which is probably not what you want.
try regex:
if (!$str.match(/^[a-zA-Z]+:\/\//))
{
$str = 'http://' + $str;
}.
hope this helps.

phpBugtracker - allow backslashes in bug comments?

I'm using phpBugtracker and I'm pretty new to php, but I would like to know how to allow backslashes in the comments. I noticed that only backslashes get striped but forward slashes stay. (I did manage to get 1 backslash to show when I put in 5)
Any help is appreciated!
$patterns = array(
'/\r/',
'/</',
'/>/',
'/\n/',
'/(bug)[[:space:]]?(#?)([0-9]+)/i', // matches bug #nn
'/cvs:([^\.\s:,\?!]+(\.[^\.\s:#,\?!]+)*)([:#](rev|r)?)?(\d\.[\d\.]+)?([\W\s])?/i', // matches cvs:filename.php, cvs:filename.php:n.nn or cvs:filename.php#revn.nn
'/<pre>/', // preformatted text
'/<\/pre>/', // preformatted text
);
$replacements = array(
'',
'<',
'>',
'<br>',
"<a href='$me?op=show&bugid=\\3'>\\1 #\\3</a>", // internal link to bug
'\\1\\6', // external link to cvs web interface
'<pre>',
'</pre>',
);
return preg_replace($patterns, $replacements, stripslashes($comments));
The reason the slashes are being stripped is because you are passing $comments through stripslashes. Just pass it in as-is and it should be ok. Worth doing some thorough testing to make sure that won't open up a security hole.

Passing string to a Javascript function does not work

I am trying to pass a string to a javascript function which opens that string in an editable text area. If the string does not contain a new line character, it is passed successfully. But when there is a new line character it fails.
My code in PHP looks like
$show_txt = sprintf("showEditTextarea('%s')", $test_string);
$output[] = '<a href="#" id="link-'.$data['test'].'" onclick="'.$show_txt.';return false;">';
And the javascript function looks like -
$output[] = '<script type="text/javascript">
var showEditTextarea = function(test_string) {
alert(test_string);
}
</script>';
The string that was successfully passed was "This is a test" and it failed for "This is a first test
This is a second test"
Javascript does not allow newline characters in strings. You need to replace them by \n before the sprintf() call.
You are getting this error because there is nothing escaping your javascript variables... json_encode is useful here. addslashes will also have to be used in the context to escape the double quotes.
$show_txt = sprintf("showEditTextarea(%s)", json_encode($test_string));
$output[] = '<a href="#" id="link-'.$data['test'].'" onclick="'.htmlspecialchars($show_txt).';return false;">';
Why don't you try replacing all spaces in the php string with \r\n before you pass it to the JavaScript function? See if that works.
If that does not work then try this:
str_replace($test, "\n", "\n");
Replacing with two \ may work as it will encapsulate.
I would avoid storing HTML or JS in PHP variables as much as possible, but if you do need to store the HTML in a PHP variable then you will need to escape the new line characters.
try
$test_string = str_replace("\n", "\\\n", $test_string);
Be sure to use double quotes in the str_replace otherwise the \n will be interpreted as literally \n instead of a new line character.
Try this code, that deletes new lines:
$show_txt = sprintf("showEditTextarea('%s')", str_replace(PHP_EOL, '', $test_string));
Or replaces with: \n.
$show_txt = sprintf("showEditTextarea('%s')", str_replace(PHP_EOL, '\n', $test_string));

Regex Replace with Backreference modified by functions

I want to replace the class with the div text like this :
This: <div class="grid-flags" >FOO</div>
Becomes: <div class="iconFoo" ></div>
So the class is changed to "icon". ucfirst(strtolower(FOO)) and the text is removed
Test HTML
<div class="grid-flags" >FOO</div>
Pattern
'/class=\"grid-flags\" \>(FOO|BAR|BAZ)/e'
Replacement
'class="icon'.ucfirst(strtolower($1).'"'
This is one example of a replacement string I've tried out of seemingly hundreds. I read that the /e modifier evaluates the PHP code but I don't understand how it works in my case because I need the double quotes around the class name so I'm lost as to which way to do this.
I tried variations on the backref eg. strtolower('$1'), strtolower('\1'), strtolower('{$1}')
I've tried single and double quotes and various escaping etc and nothing has worked yet.
I even tried preg_replace_callback() with no luck
function callback($matches){
return 'class="icon"'.ucfirst(strtolower($matches[0])).'"';
}
It was difficult for me to try to work out what you meant, but I think you want something like this:
preg_replace('/class="grid-flags" \>(FOO|BAR|BAZ)/e',
'\'class="icon\'.ucfirst(strtolower("$1")).\'">\'',
$text);
Output for your example input:
<div class="iconFoo"></div>
If this isn't what you want, could you please give us some example inputs and outputs?
And I have to agree that this would be easier with an HTML parser.
Instead of using the e(valuate) option you can use preg_replace_callback().
$text = '<div class="grid-flags" >FOO</div>';
$pattern = '/class="grid-flags" >(FOO|BAR|BAZ)/';
$myCB = function($cap) {
return 'class="icon'.ucfirst($cap[1]).'" >';
};
echo preg_replace_callback($pattern, $myCB, $text);
But instead of using regular expressions you might want to consider a more suitable parser for html like simple_html_dom or php's DOM extension.
This works for me
$html = '<div class="grid-flags" >FOO</div>';
echo preg_replace_callback(
'/class *= *\"grid-flags\" *\>(FOO|BAR|BAZ)/'
, create_function( '$matches', 'return \'class="icon\' . ucfirst(strtolower($matches[1])) .\'">\'.$matches[1];' )
, $html
);
Just be aware of the problems of parsing HTML with regex.

Categories