I am using this function to translate stuff:
function t($string)
{
global $_ACTIVE_LANGUAGE;
if(is_array($_ACTIVE_LANGUAGE) && array_key_exists($string,$_ACTIVE_LANGUAGE) )
{
return (!empty($_ACTIVE_LANGUAGE[$string])) ? $_ACTIVE_LANGUAGE[$string] : $string;
} else {
return $string;
}
}
It works well, I put t('hola') and if there's the english file with the array 'hola' => 'hello' it translates it.
However, now I want to be able to translate strings which can contain more text than just the string, like this example:
$string1 = 'download-file-justin-bieber-awesome-voice.html';
$string2 = 'view-file-rihanna-very-sexy.html';
$string3 = 'mostseen12345.html';
$string4 = 'incredible:stuff-and:real-things.html';
$array = array
(
'download-file' => 'descargar-archivo',
'view-file' => 'ver-archivo',
'mostseen' => 'masvistos',
'incredible:stuff' = 'cosas:increibles'
}
I want the script to be able to translate the parts in the keys of the array in the given strings. Is this possible at all?
You could check out str_replace() at the php-manual.
$from = array('download-file','view-file','mostseen','incredible:stuff');
$to = array('descargar-archivo','ver-archivo','masvistos','cosas:increibles');
$translated_string = str_replace($from,$to,$original_string);
Related
i have a string and i need to add some html tag at certain index of the string.
$comment_text = 'neethu and Dilnaz Patel check this'
Array ( [start_index_key] => 0 [string_length] => 6 )
Array ( [start_index_key] => 11 [string_length] => 12 )
i need to split at start index key with long mentioned in string_length
expected final output is
$formattedText = '<span>#neethu</span> and <span>#Dilnaz Patel</span> check this'
what should i do?
This is a very strict method that will break at the first change.
Do you have control over the creation of the string? If so, you can create a string with placeholders and fill the values.
Even though you can do this with regex:
$pattern = '/(.+[^ ])\s+and (.+[^ ])\s+check this/i';
$string = 'neehu and Dilnaz Patel check this';
$replace = preg_replace($pattern, '<b>#$\1</b> and <b>#$\2</b> check this', $string);
But this is still a very rigid solution.
If you can try creating a string with placeholders for the names. this will be much easier to manage and change in the future.
<?php
function my_replace($string,$array_break)
{
$break_open = array();
$break_close = array();
$start = 0;
foreach($array_break as $key => $val)
{
// for tag <span>
if($key % 2 == 0)
{
$start = $val;
$break_open[] = $val;
}
else
{
// for tag </span>
$break_close[] = $start + $val;
}
}
$result = array();
for($i=0;$i<strlen($string);$i++)
{
$current_char = $string[$i];
if(in_array($i,$break_open))
{
$result[] = "<span>".$current_char;
}
else if(in_array($i,$break_close))
{
$result[] = $current_char."</span>";
}
else
{
$result[] = $current_char;
}
}
return implode("",$result);
}
$comment_text = 'neethu and Dilnaz Patel check this';
$my_result = my_replace($comment_text,array(0,6,11,12));
var_dump($my_result);
Explaination:
Create array parameter with: The even index (0,2,4,6,8,...) would be start_index_key and The odd index (1,3,5,7,9,...) would be string_length
read every break point , and store it in $break_open and $break_close
create array $result for result.
Loop your string, add , add or dont add spann with break_point
Result:
string '<span>neethu </span>and <span>Dilnaz Patel </span> check this' (length=61)
I'v recently came accross a problem with some code as shown below:
$key = "upload_8_fid_aids.tmp";
public function to_key($key) {
$s = $this->table;//$s = kv
foreach((array)$key as $k=>$v) {
$s .= '-'.$this->primarykey[$k].'-'.$v;
}
return $s;
}
There's a (array)$key signature out there in the foreach loop,the first thing I'm stucking in is the "array" that prefixed with the variabls $k,what does this mean?The very first idea that hit upon me is that it converts the $k to an array,though,the variable $k is a string,is it plausible to convert string to array in php?I think it is unreasonable.So what does that array mean?
Thanks in advance!
When you cast a string to an array in PHP it becomes an array with the string pushed to it.
Example:
$test = "This is a string!";
print_r((array) $test);
Output:
Array
(
[0] => This is a string!
)
That said I find the code strange, I don't see the need for the loop, it could just be:
$key = "upload_8_fid_aids.tmp";
public function to_key($key) {
$s = $this->table; //$s = kv
$s .= '-' . $this->primarykey[0] . '-' . $key;
return $s;
}
Any type enclosed in parentheses is telling PHP to cast the following thing to that type.
In this case, it's a cheap way to avoid having to check if( is_array($key)), by just forcing it to be one.
Converting an object to an array:
<?php
/*** create an object ***/
$obj = new stdClass;
$obj->foo = 'foo';
$obj->bar = 'bar';
$obj->baz = 'baz';
/*** cast the object ***/
$array = (array) $obj;
/*** show the results ***/
print_r( $array );
?>
Result:
Array
(
[foo] => foo
[bar] => bar
[baz] => baz
)
I currently do search and replace for a web page template like this:
$template = <<<TEMP
<html>
<head>
<title>[{pageTitle}]</title>
</head>
[{menuA}]
[{menuB}]
[{bodyContent}]
</html>
<<<TEMP;
The above is placed in a separate file.
Then, I do:
$template = str_replace("[{pageTitle}]",$pageTitle,$template);
$template = str_replace("[{menuA}]",$menuA,$template);
$template = str_replace("[{menuB}]",$menuB,$template);
$template = str_replace("[{bodyContent}]",$bodyContent,$template);
//Some 10 more similar to the above go here.
echo $template;
The problem is, there are some 15 in total just like the ones above.
Is there a better/cleaner/professional way to do this (either the search and replace, or do the entire thing differently). I find this very messy and unprofessional.
Yes, you can define array of things you want to replace and another array with things to replace with.
$array1 = array("[{pageTitle}]", "[{menuA}]");
$array2 = array($pageTitle, $menuA);
$template = str_replace($array1 , $array2 , $template);
By modifying ljubiccica's answer. You can create associative array with variables and values and then replace them:
$array=array(
'pageTitle'=>$pageTitle,
'menuA'=> $menuA,
);
$addBrackets = function($a)
{
return '[{'.$a.'}]';
};
$array1 = array_keys($array);
$array1 = array_map($addBrackets,$array1);
$array2 = array_values($array);
$template = str_replace($array1 , $array2 , $template);
Don't reinvent the wheel, use existing template engines. I suggest twig, because it's simple and fast!
The best way is to use an existing library like Smarty or Twig.
If you want to roll your own templating solution you could use regular expressions:
// Just an example array
$values = array('pageTitle' => 'foo', 'menuA' => 'bar');
$offset = 0;
while(preg_match('/\[\{([a-zA-Z]+)\]\}/', $template, $matches,
PREG_OFFSET_CAPTURE, $offset)) {
$varname = $matches[0][3];
$value = isset($values[$varname]) ? $values[$varname] : "Not found!";
$template = str_replace('[{'.$varname.'}]', $value, $template);
$offset = $matches[1];
}
If you don't like associative arrays, you can do this instead:
$value = isset($$varname)? $$varname : "Not found";
But I'd advise against that because it could expose variable you don't want to be exposed.
what about using a regular expression. something like the below:
$matches = array();
preg_match_all("/\[\{.*?\}\]/", $template, $matches);
foreach ($matches[0] as $match){
// this will replace the '[{','}]' braces as we don't want these in our file name
$var = str_replace("[{", "", $match);
$var = str_replace("}]", "", $var);
// this should pull in the file name and continue the output
$template = str_replace($match, $$var, $template);
}
I haven't tested it but this way you wouldn't have to know what you need to replace? It would replace what's in your [{text}] tags with $text for example?
I figured out that something like this actually works:
$foo = 'bar';
$baz = 'foo';
$test = 'Test [{foo}] and [{baz}]';
$test1 = preg_replace("/\[{(.*?)}\]/e", "$$1", $test);
$test2 = preg_replace_callback("/\[{(.*?)}\]/", function($v) use($foo, $baz)
{
return ${$v[1]};
}, $test);
var_dump($test1); //string 'Test bar and foo' (length=16)
var_dump($test2); //string 'Test bar and foo' (length=16)
So in your case:
$template= preg_replace("/\[{(.*?)}\]/e", "$$1", $template);
Edit:
You can also chekck if the variable is set like this:
$foo = 'bar';
$baz = 'foo';
$test = 'Test [{foo}] and [{baz}] or [{ble}]';
$test1 = preg_replace("/\[{(.*?)}\]/e", "isset($$1) ? $$1 : '$$1';", $test);
var_dump($test1); //string 'Test bar and foo or $ble' (length=24)
I receive from my MySQL database a multidimensional array
Array
(
[0] => Array
(
[page] => categorypropose
[value] => baby-sitters
[id] => 357960
)
[1] => Array
(
[page] => categorysearch
[value] => adéquate pour garder
[id] => 357961
)
...
)
In this array, I have some ISO-8859-1 to UTF8 conversion to do via a 'homemade' function "loadtext".
But when I do this :
$array = $query->result_array();
foreach($array as &$k)
{
foreach ($k as &$value)
{
//Works
$value = $this->loadtext($value, 'ISO-8859-1');
}
}
//Back to normal as $this->loadtext never existed
print_r($array);
It doesn't conserve the changes (When I echo $value, it works, but the modification is not kept at the end ...)
EDIT : This is the function loadtext that I am oblige to use (actually, I didn't make it but I have to use it ...)
function loadtext($text,$charset){
$text = stripslashes($text);
if($charset!="UTF-8")
$text = iconv("UTF-8",$charset,$text);
$text = str_replace(" :"," :",$text);
$text = str_replace(" ;"," ;",$text);
$text = str_replace(" !"," !",$text);
$text = str_replace(" ?"," ?",$text);
$text = str_replace(" ."," .",$text);
$text = str_replace(" …"," …",$text);
return $text;
}
You could try it like this:
$array = $query->result_array();
foreach($array as &$k)
{
foreach ($k as $i => &$value)
{
//Works
$k[$i] = $this->loadtext($value, 'ISO-8859-1');
}
}
//Back to normal as $this->loadtext never existed
print_r($array);
But better yet, you could try using the MySQL function CONVERT() in your query so that the strings you get back are already in UTF8 format.
http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html
At the very least, use PHP's mb_convert_encoding() instead of your homemade function. There's no reason to reinvent the wheel.
http://jp2.php.net/manual/en/function.mb-convert-encoding.php
I found a simple answer myself which works very wellfor me bur using another method in php to change the value i get from mysql result
// ur array from mysql
$array = $query->result_array();
//try it works 100 % for me just one line of code to modify
$result= iconv('UTF-8', 'ASCII//TRANSLIT',$array);
source : php.net
// or if doesnt work then u can try like this to modify u can put it inside a foreach loop where you are loopin values
$page = array['page']; // to acces that element in the array where to modify
$result= iconv('UTF-8', 'ASCII//TRANSLIT',$page);
It occurred to me that there's another solution to this particular problem that avoids the issue of modifying an array by reference altogether.
$array = array_map(function ($row) {
return array_map(function ($col) { return mb_convert_encoding($col, 'ISO-8859-1'); }, $row);
}, $query->result_array());
This uses anonymous functions which are only available since PHP 5.3 so, if you have something older, you'll have to implement it differently and it might not be worth the trouble but I think it's a pretty good way to go.
Also, it may be more efficient/look cleaner to do it like this:
$colFn = function ($col) { return mb_convert_encoding($col, 'ISO-8859-1'); };
$rowFn = function ($row) use ($colFn) { return array_map($colFn, $row); };
$array = array_map($rowFn, $query->result_array());
I have a text file and I want to remove some lines that contain specific words
<?php
// set source file name and path
$source = "problem.txt";
// read raw text as array
$raw = file($source) or die("Cannot read file");
now there's array from which I want to remove some lines and want to use them so on.
As you have each line of your file in a row of an array, the array_filter function might interest you (quoting) :
array array_filter ( array $input [, callback $callback ] )
Iterates over each value in the input
array passing them to the callback
function. If the callback
function returns true, the current
value from input is returned into the
result array. Array keys are
preserved.
And you can use strpos or stripos to determine if a string is contained in another one.
For instance, let's suppose we have this array :
$arr = array(
'this is a test',
'glop test',
'i like php',
'a badword, glop is',
);
We could define a callback function that would filter out lines containing "glop" :
function keep_no_glop($line) {
if (strpos($line, 'glop') !== false) {
return false;
}
return true;
}
And use that function with array_filter :
$arr_filtered = array_filter($arr, 'keep_no_glop');
var_dump($arr_filtered);
And we'd get this kind of output :
array
0 => string 'this is a test' (length=14)
2 => string 'i like php' (length=10)
i.e. we have removed all the lines containing the "badword" "glop".
Of course, now that you have the basic idea, nothing prevents you from using a more complex callback function ;-)
Edit after comments : here's a full portion of code that should work :
First of all, you have your list of lines :
$arr = array(
'this is a test',
'glop test',
'i like php',
'a badword, glop is',
);
Then, you load the list of bad words from a file :
And you trim each line, and remove empty lines, to make sure you only end up with "words" in the $bad_words array, and not blank stuff that would cause troubles.
$bad_words = array_filter(array_map('trim', file('your_file_with_bad_words.txt')));
var_dump($bad_words);
The $bad_words array contains, from my test file :
array
0 => string 'glop' (length=4)
1 => string 'test' (length=4)
Then, the callback function, that loops over that array of bad words:
Note : using a global variable is not that nice :-( But the callback function called by array_filter doesn't get any other parameter, and I didn't want to load the file each time the callback function is called.
function keep_no_glop($line) {
global $bad_words;
foreach ($bad_words as $bad_word) {
if (strpos($line, $bad_word) !== false) {
return false;
}
}
return true;
}
And, as before, you can use array_filter to filter the lines :
$arr_filtered = array_filter($arr, 'keep_no_glop');
var_dump($arr_filtered);
Which, this time, gives you :
array
2 => string 'i like php' (length=10)
This will remove all rows that have a blacklisted word in it:
$rows = file("problem.txt");
$blacklist = "foo|bar|lol";
foreach($rows as $key => $row) {
if(preg_match("/($blacklist)/", $row)) {
unset($rows[$key]);
}
}
file_put_contents("solved.txt", implode("\n", $rows));
Or, if you are using PHP 5.3, you can use a lambda function with array_filter:
$rows = file("problem.txt");
$blacklist = "foo|bar|lol";
$rows = array_filter($rows, function($row) {
return preg_match("/($blacklist)/", $row);
});
file_put_contents("solved.txt", implode("\n", $rows));
Prior to PHP 5.3, a solution using array_filter would actually use up more rows than the first solution I posted, so I'll leave that out.
$file=file("problem.txt");
$a = preg_grep("/martin|john/",$file,PREG_GREP_INVERT );
print_r($a);
Check out the strpos function. It can tell you if a string contains another string or not (and where exactly the first string is in the second). You would use it like this:
$good = array();
$bad_words = array('martin', 'methew');
// for every line in the file
foreach($raw as $line) {
// check for each word we want to avoid
foreach($bad_words as $word) {
// if this line has a trigger word
if(strpos($line, $word) !== false) {
// skip it and start processing the next
continue 2;
}
}
// no triggers hit, line is clean
$good[] = $line;
}
Now you would have a list of only clean lines in $good.
If you have a long string rather than a file and you want to remove all string lines that has specific words. You can use this:
$string="I have a long string\n
That has good words inside.\n
I love my string.\n
//add some words here\n";
$rows = explode("\n",$string);
$unwanted = "tring|\/\/";
$cleanArray= preg_grep("/$unwanted/i",$rows,PREG_GREP_INVERT);
$cleanString=implode("\n",$cleanArray);
print_r ( $cleanString );
This removes that has lines contain "tring" and "//".
Assuming that you have an array of "bad words":
<?php
foreach ($raw as $key=>$line)
{
foreach ($badwords as $w)
{
if ( strpos($line, $w) !== false )
unset($raw[$key]);
}
}
?>
<?php
$source = "problem.txt";
$raw = file_get_contents($source) or die("Cannot read file");
$wordlist = "martin|methew";
$raw = preg_replace("/($wordlist)/i", "", $raw);
file_put_contents($source, $raw);
?>