How to separate text with PHP [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Well I am trying to make a simple php system.
Anywise I need to separate the text when I want to add it to the database.
So for example I want to add:
abc:123
I want that the : will be the separater, so it'll look like this:
abc
123
And then both will go to a different table.
Could someone help me with this? As I am not an experience PHP coder, yet I am willing to learn how to do this.
Kind regards

This is pretty basic stuff..
$data = explode(':','abc:123');
foreach($data as $word)
{
// some code here
}

Use Split:
<?php
$data = "abc:123";
list ($var1, $var2) = split (':', $data);
echo "Var1: $var1; Var2: $var2;<br />\n";
?>

You can achieve this using explode.
abc:123
Is a string. Let's define it as a variable:
$origin = "abc:123";
You can split the string, using : as the separator.
$separator = ":";
$exploded = explode($separator, $origin);
Now you have an array which you can use to access abc and 123 individually.
$pre = $exploded[0];
$post = $exploded[1];
You don't know how many splits there will be?
That's okay. Your array simply increases, meaning you can simply loop through the array and handle the values.
foreach ($exploded as $split)
{
// Do something with $split
}

Related

Regex for extract numbers and extension of string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I use code below for extract numbers and file name of strings with problem standardization
30183308__90_.jpeg
30193253-(100).jpg
30193253__100__.jpg
30193253_ _100_ _.jpg
Use this function
public function refactorFileName($filename)
{
$array = preg_split("/[^A-Za-z0-9]/", $filename);
foreach($array as $key => $value) {
if($value == "") {
unset($array[$key]);
}
}
$array = array_values($array);
$standardFilename = $array[0].'.'.$array[2];
$indexFile = $array[1];
return compact("indexFile","standardFilename");
}
$filename = '30193253_ _100_ _.jpg';
extract(refactorFileName($filename));
echo "New File name -> ".$standardFilename.PHP_EOL;
echo "Index for file -> ".$indexFile.PHP_EOL;
This show (correct):
New File name -> 30193253.jpg
Index for file -> 100
I think there're a better code for regex expresion.
EDIT:
It's possible better code on preg_split or better code in general for this question?
Two things: 1) It will be easier if you put a quantifier in your pattern (to avoid the useless foreach after). (Note that preg_split has also the option PREG_SPLIT_NO_EMPTY to avoid empty items.)
2) sometimes too much verbosity kills the verbosity.
Your can rewrite it this way:
function refactorFileName($filename) {
$p = preg_split('~[\W_]+~', $filename, 3);
return [ 'indexFile' => $p[1], 'standardFilename' => "$p[0].$p[2]" ];
}
Or if you want to be more verbose:
function refactorFileName($filename) {
list($name, $index, $ext) = preg_split('~[\W_]+~', $filename, 3);
return [ 'indexFile' => $index, 'standardFilename' => "$name.$ext" ];
}
(As an aside, when you already have a working code, ask your question on codereview instead of SO)

Reliably retrieve PHP constant from a file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Latest Edit:
Well, I came up with fairly "reliable" :) solution in form of a (portable) function, but since some ppl here got irked enough by not understanding the problem and blocked this question (a military solution: kill what you do not understand), I cannot post it here. Pity.
I have a set of files, which contain constants, like below.
define ('LNG_GSU_LNK_LBL', '[details]');
define( 'LNG_METHODCROSS_GSU_CLS' ,'class');
define('GSU_METH' , 'method');
define ( 'CROSS_GSU_ACTION_NO_REMOVE', 'cannot remove \' module \'(is); deployed');
What would be most reliable method to retrieve constant names and values from given, selected file.
EDIT:
I need to get these constants into array, without defining them actually, directly by reading file, e.g.:
array('LNG_GSU_LNK_LBL'=>'[details]','LNG_METHODCROSS_GSU_CLS'=> 'class')
... etc
EDIT 2:
So far I got this far:
$file_array = file($path, FILE_SKIP_EMPTY_LINES);
//implode lang file into a string removing php tags
$string1 = implode('', $file_array);
$string2 = str_replace(array(''), '', $string1);
//regex removing content between markers
$regex = '/\/\*.+?\*\//si';
$replace_with = '';
$replace_where = $string2;
$string3 = preg_replace($regex, $replace_with, $replace_where);
//regex: remove multiple newlines
$string4 = preg_replace("/\n+/", "\n", $string3);
EDIT 3:
expected result
array (
'LNG_GSU_LNK_LBL' => '[details]',
'LNG_METHODCROSS_GSU_CLS' => 'class',
'GSU_METH' => 'method',
'CROSS_GSU_ACTION_NO_REMOVE' => 'cannot remove \' module \'(is); deployed'
);
If you dont want to include the file, then you should use: token_get_all().
Otherwise, you should require/include the file containing them and you can iteratively use get_defined_constants():
$all = array();
$consts = get_defined_constants();
foreach($consts as $k=>$v){
if (strpos($k,"LNG")===0 && !isset($all[$k]))
$all[$k]=$v;
}
Note that parsing php source code is like parsing HTML with regex, better bet avoid it.
Building on dynamic's answer, include the file within another, separate, web accessible file, that is not loaded within your current application (so will have no other user defined constants at run time):
//standalone.php
include "that_file.php";
$consts = get_defined_constants(true);
$newUserConsts = $consts['user'];
echo json_encode($newUserConsts);
//within your application
$newUserConsts = json_decode(file_get_contents('http://yoursite.com/standalone.php'));
Or if you cant make a separate web accessible file:
$consts = get_defined_constants(true);
$existingUserConsts = $consts['user'];
include "that_file.php";
$consts = get_defined_constants(true);
$newUserConsts = $consts['user'];
var_dump(array_diff_key($newUserConsts, $existingUserConsts));

"\u00e1n" to "á" in PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am receiving an external file with strings, I have no control over that file but I receive special characters as this (i think it's unicode?) sequence \u00e1n.
Is there anyway to convert this kind of char sequences to their "readable" counterparts?
Thanks!
EDIT:
I am calling a url that gives me a list with names of persons:
Tom\u00e1nsson\n
Eriksen\n
Gilverto\n
I am reading the names and showing them in my site.
EDIT
Now, I've figured out the correct, working answer based on the article I found. Here is it:
function unicode2utf8($str) {
$a=json_decode(str_replace("\n","<br>",'["'.$str.'"]'));
return str_replace("<br>","\n",$a[0]);
}
PHP:
echo unicode2utf8("Tom\u00e1nsson\n Eriksen\n Gilverto\n");
Output:
Tománsson
Eriksen
Gilverto
ORIGINAL
I've found an article about the same problem here ( http://www.welefen.com/php-unicode-to-utf8.html )
The solution is the following function
function unicode2utf8($str){
if(!$str) return $str;
$decode = json_decode($str);
if($decode) return $decode;
$str = '["' . $str . '"]';
$decode = json_decode($str);
if(count($decode) == 1){
return $decode[0];
}
return $str;
}
I've tried it with
echo unicode2utf8("\u00e1");
Output:
á

Writing array to a file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
In the program below
$array[name1][0] = 'name';
$array[name1][1] = '11';
$array[name2][0] = 'name2';
$array[name2][1] = '11';
$fileName = "file.php"
$fp = fopen($fileName,'w');
$msg = $array;
fwrite($fp,$msg);
fclose($fp);
In this file "file.php", i want to write an array...such tha its read like
<?
$array[name1][0] = 'name';
$array[name1][1] = '11';
$array[name2][0] = 'name2';
$array[name2][1] = '11';
but it's not working.
Use json_encode or serialize to get a storable (and compact) representation of your data structure, then json_decode or unserialize to get it back.
The var_export function does just that:
fprintf($fp, '<?php $array = %s;', var_export($array, true));
It generates valid PHP code and you can include the file after that:
include "file.php";
Note that you can return from a PHP file, so this would work too:
fprintf($fp, '<?php return %s;', var_export($array, true));
And then:
$array = include "file.php";
Alternatives to generating PHP code are json_encode/json_decode, or serialize/unserialize.
You can do it like this:
fwrite($fp,print_r($msg,true));
If you want to be able to read the file later and get an PHP array back, then you need to "serialize" the array:
and later
$array = unserialize(file_get_contents("test.data"));
if it should look readable in the file, you var_export($array,1) or print_r($array,1) and store their output.
The closest you're going to get, natively, is by using var_export and writing its return value to the file.
Failing that, you should implement something to build that format from an Array.

php replace of keys inside a string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have an array of keys and a medium/long string.
I need to replace only max 2 keys that I found in this text with the same keys wrapped with a link.
Thanks.
ex.:
$aKeys = array();
$aKeys[] = "beautiful";
$aKeys[] = "text";
$aKeys[] = "awesome";
...
$aLink = array();
$aLink[] = "http://www.domain1.com";
$aLink[] = "http://www.domain2.com";
$myText = "This is my beautiful awesome text";
should became "This is my <a href='http://www.domain1.com'>beautiful</a> awesome <a href='http://www.domain2.com'>text</a>";
Don't really understood what you need but you can do something like:
$aText = explode(" ", $myText);
$iUsedDomain = 0;
foreach($aText as $sWord){
if(in_array($sWord, $aKeys) and $iUsedDomain < 2){
echo "<a href='".$aLink[$iUsedDomain++]."'>".$sWord."</a> ";
}
else{ echo $sWord." "; }
}
So, you could use a snippet like this. I recommend you to update this code by using clean classes instead of stuff like global - just used this to show you how you could solve this with less code.
// 2 is the number of allowed replacements
echo preg_replace_callback('!('.implode('|', $aKeys).')!', 'yourCallbackFunction', $myText, 2);
function yourCallbackFunction ($matches)
{
// Get the link array defined outside of this function (NOT recommended)
global $aLink;
// Buffer the url
$url = $aLink[0];
// Do this to reset the indexes of your aray
unset($aLink[0]);
$aLink = array_merge($aLink);
// Do the replace
return ''.$matches[1].'';
}

Categories