I have a script written in PHP but there is a problem
this code does not accept Unicode text. when I pass Unicode text to this code, it returns some invalid characters.
public static function compile(&$subject, $replace, $with) {
$placeholders = array_combine($replace, $with);
$condition = '{[a-z0-9\_\- ]+:[a-z_]+}';
$inner = '((?:(?!{/?if).)*)';
$pattern = '#{if ('.$condition.')}'.$inner.'{/if}#is';
while (preg_match($pattern, $subject, $match)) {
$placeholder = $match[1];
$content = $match[2];
// if empty value remove whole line
// else show line but remove pseudo-code
$subject = preg_replace($pattern,
empty($placeholders[$placeholder]) ? '' : addcslashes($content, '$'),
$subject,
1);
}
}
please help me.
AFAIK, for unicode you need to use multibyte string methods:
http://php.net/manual/en/ref.mbstring.php
Related
I'm trying to create a simple PHP find and replace system by looking at all of the images in the HTML and add a simple bit of code at the start and end of the image source. The image source has something like this:
<img src="img/image-file.jpg">
and it should become into this:
<img src="{{media url="wysiwyg/image-file.jpg"}}"
The Find
="img/image-file1.jpg"
="img/file-2.png"
="img/image3.jpg"
Replace With
="{{media url="wysiwyg/image-file.jpg"}}"
="{{media url="wysiwyg/file-2.png"}}"
="{{media url="wysiwyg/image3.jpg"}}"
The solution is most likely simple yet from all of the research that I have done. It only works with one string not a variety of unpredictable strings.
Current Progress
$oldMessage = "img/";
$deletedFormat = '{{media url="wysiwyg/';
$str = file_get_contents('Content Slots/Compilied Code.html');
$str = str_replace("$oldMessage", "$deletedFormat",$str);
The bit I'm stuck at is find the " at the end of the source to add the end of the required code "}}"
I don't like to build regular expressions to parse HTML, but it seems that in this case, a regular expression will help you:
$reg = '/=["\']img\/([^"\']*)["\']/';
$src = ['="img/image-file1.jpg"', '="img/file-2.png"', '="img/image3.jpg"'];
foreach ($src as $s) {
$str = preg_replace($reg, '={{media url="wysiwyg/$1"}}', $s);
echo "$str\n";
}
Here you have an example on Ideone.
To make it works with your content:
$content = file_get_contents('Content Slots/Compilied Code.html');
$reg = '/=["\']img\/([^"\']*)["\']/';
$final = preg_replace($reg, '={{media url="wysiwyg/$1"}}', $content);
Here you have an example on Ideone.
In my opinion what you are doing is not the best way this can be done. I would use abstract template for this.
<?php
$content = file_get_contents('Content Slots/Compilied Code.html');
preg_match_all('/=\"img\/(.*?)\"/', $content, $matches);
$finds = $matches[1];
$abstract = '="{{media url="wysiwyg/{filename}"}}"';
$concretes = [];
foreach ($finds as $find) {
$concretes[] = str_replace("{filename}", $find, $abstract);
}
// $conretes[] will now have all matches formed properly...
Edit:
To return full html use this:
<?php
$content = file_get_contents('Content Slots/Compilied Code.html');
preg_match_all('/=\"img\/(.*)\"/', $content, $matches);
$finds = $matches[1];
$abstract = '="{{media url="wysiwyg/{filename}"}}"';
foreach ($finds as $find) {
$content = preg_replace('/=\"img\/(.*)\"/', str_replace("{filename}", $find, $abstract), $content, 1);
}
echo $content;
My code:
preg_match_all('(\[(link)\](.*?)\[/(link)\])', $message, $matches);
$matches = $matches[2];
foreach($matches as $match){
//CHECK LINK AND VERIFY
$message = preg_replace('(\[(link)\]('.$match.')\[/(link)\])', ''.$match.'', $message);
}
As you can see here https://mcskripts.dk/forum/id/286
The script works, but it can't replace links containing () or ?
Anyway i can fix that?
Sry, if i make a repost, just don't know if i can comment on old posts, and get a response.
You could use a single preg_replace:
$message = preg_replace('~\[link\](.+?)\[/link\]~', '$1', $message);
If you want to validate the links before replace, use preg_replace_callback:
$message = preg_replace_callback(
'~\[link\](.+?)\[/link\]~',
function($match) {
# call your function to validate the link
if (validate_link($match[1])) {
return ''.$match[1].'';
} else {
return 'What you want when validation fail!';
}
},
$message
);
i have a problem with a function in php i want to convert all the "\n" in a clear space, i've tried with this, but it doesn't work
function clean($text) {
if ($text === null) return null;
if (strstr($text, "\xa7") || strstr($text, "&")) {
$text = preg_replace("/(?i)(\x{00a7}|&)[0-9A-FK-OR]/u", "", $text);
}
$text = htmlspecialchars($text, ENT_QUOTES, "UTF-8");
if (strstr($text, "\n")) {
$text = preg_replace("\n", "", $text);
}
return $text;
}
This is wat i want remove
The site: click here
If you literally have "\n" in your text, which appears to be the case from your screenshots, then do the following:
$text = str_replace("\\n", '', $text);
\n is a special character in PHP that creates new lines, so we need to add the escape character \ in front of it in order to remove text instances of "\n".
preg_replace() seems to work better this way:
$text = preg_replace('/\n/',"",$text);
Single quotes enforce no substitution when sending your pattern to the parser.
class Something
{
public static function compile(&$subject, $replace, $with) {
$placeholders = array_combine($replace, $with);
$condition = '{[a-z0-9\_\- ]+:[a-z_]+}';
$inner = '((?:(?!{/?if).)*?)';
$pattern = '#{if\s?('.$condition.')}'.$inner.'{/if}#is';
while (preg_match($pattern, $subject, $match)) {
$placeholder = $match[1];
$content = $match[2];
// if empty value remove whole line
// else show line but remove pseudo-code
$subject = preg_replace($pattern,
empty($placeholders[$placeholder]) ? '' : addcslashes($content, '$'),
$subject,
1);
}
}
}
I have a html code area to play on. Dompdf handles the rest for converting my form to pdf. This class code was almost premade. It gives me freedom to use ;
{if {dil:value}} <div class="english">ENGLISH</div> {/if}
something like that in html area. But it was only checking if radio button is empty or not. But I want to learn which option is selected. So I want to use a code like ;
{if {dil:value}=='ENGLISH'} <div class="english">ENGLISH</div> {/if}
I converted empty check line with manual equality check to see if it works;
// if empty value remove whole line
// else show line but remove pseudo-code
$subject = preg_replace($pattern,
$placeholders[$placeholder]=='english' ? '' : addcslashes($content, '$'),
$subject,
1);
And it worked but without a freedom of course(only if radio equals to english). I'm so new to regex, so I couldn't figure it out. I tried to add $equality variable so I would use my code many times with different checks;
class Something
{
public static function compile(&$subject, $replace, $with) {
$placeholders = array_combine($replace, $with);
$condition = '{[a-z0-9\_\- ]+:[a-z_]+}';
$inner = '((?:(?!{/?if).)*?)';
$equality = '(?<=~)[^}]*(?=~)';
$pattern = '#{if\s?('.$condition.')'.$equality.'}'.$inner.'{/if}#is';
while (preg_match($pattern, $subject, $match)) {
$placeholder = $match[1];
$content = $match[2];
// if empty value remove whole line
// else show line but remove pseudo-code
$subject = preg_replace($pattern,
$placeholders[$placeholder]==$equality ? '' : addcslashes($content, '$'),
$subject,
1);
}
}
}
with this code on html area;
{if {dil:value}~'ENGLISH'~} <div class="english">ENGLISH</div> {/if}
I really believed that it would work, but it didn't :) Even pattern didn't get erase after converting to pdf so I can read my code under the pdf file.
I may be missing something about $match too. With equality variable included so $match might get third array I guess. So I also tried to add this but that didn't work too;
while (preg_match($pattern, $subject, $match)) {
$placeholder = $match[1];
$equality = $match[2];
$content = $match[3];
Well my goal is to put check icons on to specific box areas on premade designed form image. I handled all textboxes with absolute positions except getting which radio button is checked.
Thank you for all your help.
I solved it like this;
class Something
{
public static function compile(&$subject, $replace, $with) {
$placeholders = array_combine($replace, $with);
$condition = '{[a-z0-9\_\- ]+:[a-z_]+}';
$inner = '((?:(?!{\/?if).)*?)';
$equality = '(~[A-ZÇŞĞÜÖİçşğüöı]+~)';
$pattern = '#{if\s?('.$condition.')}'.$equality.''.$inner.'{\/if}#is';
while (preg_match($pattern, $subject, $match)) {
$placeholder = $match[1];
$equality = $match[2];
$content = $match[3];
$equality = substr($equality, 1, -1);
// if empty value remove whole line
// else show line but remove pseudo-code
$subject = preg_replace($pattern,
$placeholders[$placeholder] == $equality ? '' : addcslashes($content, '$'),
$subject,
1);
}
}
}
I changed my equality regex to support Utf-8 characters plus changed other regexes a bit. There were non excaped slashes. And finally I can use it at html like this;
{if {language:value}}~FRENCH~<div class="english">ENGLISH</div>{/if}
So first match gets radio button value, second match is my equality check, and third match is what will be written if equality is wrong. Yep I know it sounds a little bit reversed mode :) So it probably won't work with radio buttons which have more than 2 options. But in my situations my all radio buttons have 2 options.
So far so good, I kinda learnt regex today :)
I'm using an old Joomla! plugin (I know, first mistake). It does some URL replacement through regex. Here is the code:
$row->text = preg_replace_callback('#href=("|\')(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)("|\')#', 'replace_links', $row->text);
The problem is that it breaks with URLs that have a hyphen in them. Any help on how I can modify it to accept hyphens would be great.
It could also be the replace_links function that breaks:
function replace_links($matches) {
$match = $matches[0];
$array = array('href=',"'", '"');
$match = str_replace($array, '',$match);
if (strpos($match, JURI::root())) {
return $matches[0];
} else {
$plugin =& JPluginHelper::getPlugin('content', 'linkdisclaimer');
$pluginParams = new JParameter( $plugin->params );
$id = $pluginParams->get('disclaimerPage');
$match = "href=\"javascript:linkDisclaimer('".rawurlencode($match)."', '".$id."');\"";
return $match;
}
}
I tried this in a regex tester and it doesn't match urls with a - in them, so I'm guessing it's the regex. Try adding a - character into the regex like so href=("|\')(https?://([-\w\.]+)+(:\d+)?(/([\w-/_\.]*(\?\S+)?)?)?)("|\'). This should allow - in the path segment after the domain. The full replacement would be like
$row->text = preg_replace_callback('#href=("|\')(https?://([-\w\.]+)+(:\d+)?(/([\w-/_\.]*(\?\S+)?)?)?)("|\')#', 'replace_links', $row->text);