extract pure text strings from php scripts for translation - php

I have project which contains bigger amount of php files. Former programmer wrote everything (texts) in english in source files together with html code and I need to make translation now. Go manually file by file and extract all texts to one lanugage file is huge pain. Is there any free tool please to extract and convert all text to e.g. variables in source files and produce just one big file with text variables to simple translation?
many thanks.
P.S. I would like to automatize this work rather than manually do it file-by-file.
Examples of code in php files:
<?php
echo "Hi back, " . $user;
?>
<center class="title">No list(s) available.</center>
<tr id="exp<?php echo $r; ?>" class="me" onmouseover="dis('<?php echo $u; ?>');"> <td>This is new statement</td></tr>

this function is gonna help you in some cases and it returns the plain text between > and <
before you start you need to replace
' (quotation)
with
\' (backslash quotation)
$text = '
<?php
echo "Hi back, " . $user;
?>
<center class="title">No list(s) available.</center>
<tr id="exp<?php echo $r; ?>" class="me" onmouseover="dis(\'<?php echo $u; ?>\');"> <td>This is new statement</td></tr>
';
the function is:
function getSentences($string){
$arr = array();
$parts = explode(">", $string);
if(count($parts) > 2){
$pattern = "/\>(.*?)</";
foreach($parts as $part){
$part = ">" . $part;
preg_match($pattern, trim($part), $matches);
if(!empty($matches[1]) AND $matches[1] != " "){
if(preg_match('/^[a-zA-Z0-9]/', $matches[1])){
$arr[] = $matches[1];
}
}
}
}else{
$pattern = "/\>(.*?)</";
preg_match($pattern, $string, $matches);
$arr[] = $matches[1];
}
return $arr;
}
and call the function by :
print_r(getSentences($text));
the output will be something like this:
Array ( [0] => No list(s) available. [1] => This is new statement )

Related

How to comment in and out php code inside a file

Using PHP how to comment in all php code inside certain php file
for example if i've the followig file
$file = 'myfile.php';
has only PHP code
<?php
$c = 'anything';
echo $c;
?>
I want using PHP to comment in (add /* just after open tag <?php and */ just before close tag ?>) to be
<?php
/*
$c = 'anything';
echo $c;
*/
?>
And also how to do the reverse bycomment out (remove /* */) to return back to
<?php
$c = 'anything';
echo $c;
?>
I've been thinking to use array_splice then doing str_replace then using implode and file_put_contents but still unable to figure out how to do this.
Update
Okay meanwhile getting some help over here, i was thinking about it and it comes to my mind this idea .... USING ARRAY!
to add block comment /* just after open tag <?php i will convert the content of that file into array
$contents = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
and then i can array push new element at position 2 with /*
and to do the reverse i will use unset($contents[1]); to unset element at postion 2 which means, /* will be gone
later on i can file_put_contents($file, $contents); to re-write the file again.
You can use PREG_REPLACE :
<?php
function uncomment($file_path) {
$current = file_get_contents($file_path);
$current = preg_replace('/\\/\\*(.+?)\\*\\//s', '$1', $current);
file_put_contents($file_path, $current);
return $current;
}
echo "<plaintext>" . uncomment("code.php");
?>
BEFORE :
AFTER :
I don't know why you want comment or uncomment the php code but I don't think it's a good way to do. I advice you to use variable or constant, like this :
One other way to enable or disable you code, is to use constant variable after the second time :
TOGGLE/UNTOGGLE COMMENT :
You will be able to do :
uncomment("code.php", "MYENV_DEBUG"); // uncomment
uncomment("code.php", "MYENV_DEBUG"); // comment
uncomment("code.php", "MYENV_DEBUG"); // uncomment
uncomment("code.php", "MYENV_DEBUG"); // comment
FIRST TIME :
SECOND TIME :
THIRD TIME :
Code :
<?php
function uncomment_header($name, $value) {
return '<?php define("' . $name . '", ' . $value . '); ?>';
}
function uncomment($file_path, $name) {
$current = file_get_contents($file_path);
$regex = '/<\\?php define\\("' . $name . '", (0|1)\\); \\?>/';
if (preg_match($regex, $current, $match)) {
$value = ($match[1] == 1) ? 0 : 1;
$current = preg_replace($regex, uncomment_header($name, $value), $current);
} else {
$header = uncomment_header($name, 1) . "\n";
$start = 'if (' . $name . '):';
$end = 'endif;';
$current = $header . $current;
$current = preg_replace('/\\/\\*(.+?)\\*\\//s', $start . '$1' . $end, $current);
}
file_put_contents($file_path, $current);
return $current;
}
echo "<plaintext>" . uncomment("code.php", "MYENV_DEBUG");
?>
There are two types of comments in PHP 1)single line comment 2)Multiple line comment for single comment in php we just type // or # all text to the right will be ignored by PHP interpreter. for example
<?php
echo "code in PHP!"; // This will print out Hello World!
?>
Result: code in PHP!
For multiple line comments multiple line PHP comment begins with " /* " and ends with " / " for example
<?php
/* This Echo statement will print out my message to the
the place in which I reside on. In other words, the World. */
echo "Hello World!";
/* echo "My name is Noman Ali!";
echo "PHP Programmer!";
*/?>
Result: Hello World!
Like this:
#canned test data, a string and the file contents are the same
$contents = <<<'CODE'
<?php
$c = 'anything';
echo $c;
?>
CODE;
$contents = preg_replace(['/<\?php\s/','/\?\>/'], ['<?php/*', '*/?>'], $contents);
echo $contents;
Output
<?php/*
$c = 'anything';
echo $c;
*/?>
Sandbox
NOTE - this will only work if the ending tag is present. In PHP the ending tag is actually optional. This will also not work on things like short tags <? or <?= although it will catch the ending tags.
Because of these edge cases it's very hard to do with regex (or any string replacement).
Valid examples of PHP code
<?php
$c = 'anything';
echo $c;
?>
//-------- no ending tag ---------
<?php
$c = 'anything';
echo $c;
//------- short tags ---------
<? echo 'foo'; ?>
//------- short echo tags ---------
<?= $foo; ?>
etc...
Good luck if you want to try to catch them all....

How can I split html value and normal string into different array in php?

Say I have string such as below:
"b<a=2<sup>2</sup>"
Actually its a formula. I need to display this formula on webpage but after b string is hiding because its considered as broken anchor tag. I tried with htmlspecialchars method but it returns complete string as plain text. I am trying with some regex but I can get only text between some tags.
UPDATE:
This seems to work with this formula:
"(c<a) = (b<a) = 2<sup>2</sup>"
And even with this formula:
"b<a=2<sup>2</sup>"
HERE'S THE MAGIC:
<?php
$_string = "b<a=2<sup>2</sup>";
$string = "(c<a) = (b<a) = 2<sup>2</sup>";
$open_sup = strpos($string,"<sup>");
$close_sup = strpos($string,"</sup>");
$chars_array = str_split($string);
foreach($chars_array as $index => $char)
{
if($index != $open_sup && $index != $close_sup)
{
if($char == "<")
{
echo "<";
}
else{
echo $char;
}
}
else{
echo $char;
}
}
OLD SOLUTION (DOESN'T WORK)
Maybe this can help:
I've tried to backslash chars, but it doesn't work as expected.
Then i've tried this one:
<?php
$string = "b&lta=2<sup>2</sup>";
echo $string;
?>
Using &lt html entity it seems to work if i understood your problem...
Let me know
Probably you can give spaces such as :
b < a = 2<sup>2</sup>
It does not disappear the tag and looks much more understanding....
You could try this regex approach, which should skip elements.
$regex = '/<(.*?)\h*.*>.+<\/\1>(*SKIP)(*FAIL)|(<|>)/';
$string = 'b<a=2<sup>2</sup>';
$string = preg_replace_callback($regex, function($match) {
return htmlentities($match[2]);
}, $string);
echo $string;
Output:
b<a=2<sup>2</sup>
PHP Demo: https://eval.in/507605
Regex101: https://regex101.com/r/kD0iM0/1

automatic convert word to link in PHP

I want write a simple code that convert special words to special link (for wiki plugin), if it's not a link!
For example suppose we have a text "Hello! How are you?!" and
we want convert are to are, but if we have Hello! How are you?! or Hello! How are you?! does not change. Because it's a link.
How can I do it in PHP?! With preg_replace?! How to?
Thanks.
It's easy.
<?php
$string = "Hello! How are you?!";
$stringTwo = "Hello! how are you?!";
function turnTheWordIntoALink($string, $word, $link) {
if(isLink($string)) {
return $string;
} else {
$string = str_replace($word, "" . $word . "", $string);
return $string;
}
}
function isLink($string) {
return preg_match("/(<a href=\".\">)/", $string);
}
echo turnTheWordIntoALink($string, 'are', 'http://google.com');
echo turnTheWordIntoALink($stringTwo, 'are', 'http://google.com');
Output:
First function output: Hello! How are you?!
Second function output: Hello! how are you?!
Alternative:
If you want to not detect <a> tags which were closed, you can use this alternative code:
$stringThree = "Hello! how <a href=\"#\">are you?!";
function turnTheWordIntoALink($string, $word, $link) {
if(isLink($string)) {
return $string;
} else {
$string = str_replace($word, "" . $word . "", $string);
return $string;
}
}
function isLink($string) {
return preg_match("/(<a href=\".\">)+(.)+(<\/a>)/", $string);
}
echo turnTheWordIntoALink($stringThree, 'are', 'http://google.com') . "\n";
This gives the output: Hello! how <a href="http://google.com">are you?!
this code is about : if there is a some URL in some phrase it will convert to a link
$word = 'hello how are you google.com, wish you good time';
$prg = "/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
if(preg_match($prg, $word, $url))
{
echo preg_replace($prg, "<a href=http://$url[0]>{$url[0]}</a>", $word);
}
else
{
echo $word;
}
To better clarify the issue:
I have a HTML code that have some tags. I want some words in that, converted to some links. But if it is a another link does not convert. See below advanced example for special word you that we want linked to the google:
This is a sample text.
Hello?! How are you?!
Are you ready?!
should be convert to:
This is a sample text.
Hello?! How are you?!
Are you ready ?!
Note that the first you changed, but that second you was not changed, because it's in the another <a> tag.
Answer:
Because of this work has issue with regular expression, this problem can solve without regular expression. Here a simple solution is given:
$data = 'Hello! This is a sample text. <br/>'.
'Hello! This is a sample text. <br/>'.
'Hello! This is a sample text. <br/>'.
'Hello! This is a sample text. <br/>'.
'Hello! This is a sample text.';
$from = " is ";
$to = '<a href="http://www.google.com" > '.$from.' </a>';
echo $data;
$data = explode($from, $data);
echo "<br><br>";
echo $data[0];
$diff = 0;
for($i=1; $i<count($data); $i++){
$n = substr_count($data[$i-1], '<a ') + substr_count($data[$i-1], '<A ');
$m = substr_count($data[$i-1], '</a>') + substr_count($data[$i-1], '</A>');
$diff += $n-$m;
if($diff==0)
echo $to.$data[$i];
else
echo $from.$data[$i];
}

Extract url from string via preg match in php

$str = 'window.location.href="http://my-site.com";'
I want to extract the url from $str. I am not that good in preg_match(). However with the following code:
preg_match('/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/', $str, $link);
if (empty($link[0])) {
echo "Nothing found!";
} else {
echo $link[0];
}
I am able to get the result http://my-site.com";. I want to customize preg_match() to exclude "; from the result. Please help!
<?php
$str = 'window.location.href="http://my-site.com";';
preg_match('/window\.location\.href="(.*?)";/', $str, $result);
echo $result[1];
//http://my-site.com
>?
http://ideone.com/YTk70i
If you dont feel comfortable with preg_* then try keeping it simple. It seems a bit of an unnecessary overhead loading the regex engine anyway for something that simple.
Try this instead :-
$str = 'window.location.href="http://my-site.com";';
$p1 = strpos($str, 'href="') + strlen('href="');
$p2 = strpos($str, '";', $p1);
$url = substr($str,$p1,$p2-$p1);
echo $p1 .PHP_EOL;
echo $p2 .PHP_EOL;
echo $url;
This yeilds the following
22
40
http://my-site.com
i.e everything between href=" and ";
Try this:
preg_match('/^window.location.href="([^"]+)";$/', $str, $link);

echo text separating every 3 words per line?

I have seen some samples using var_dump, but I I would rather use a simple echo, if it's possible.
It should look like this using echo:
This is a
simple text
I just wrote
Using var_dump:
function split3($text)
{
$array = array();
foreach(explode(' ',$text) as $i=>$word)
{
if($i%3) {
$array[floor($i/3)] .= ' '.$word;
} else {
$array[$i/3] = $word;
}
}
return $array;
}
$text = "This is a simple text I just wrote";
var_dump(split3($text));
Your sample output is a bit wrong compare to your question.
If the output is like this.
This is a
simple text I
just wrote
Then replace the var_dump(split3($text)); with this
$splitedText = split3($text);
foreach($splitedText as $value){ //Just print the array content
echo $value . "<br />"; //I use <br /> as a new line
}

Categories