Hello i have a script that extract company names from a string. I want that the extracted names to be converted to php variable. So for example first result Real Coffee Sweeden must be converted to $RealCoffeeSweeden = 0 so i can assign a value to it
$test='/showname/0406741848 : Real Coffee Sweeden
/showname/0406741849 : Healthzone SE
/showname/16133663413 : FREE
/showname/16133663414 : RadioPlantes Canada
/showname/16133663417 : Dealsoftoday.Eu Canada
/showname/16136995593 : FREE
/showname/16136995594 : Club White Smile Canada
/showname/16138007442 : FREE
/showname/16138007547 : Mybitwave.com Canada
/showname/16465596150 : BABY
/showname/16465696956 : FREE
/showname/16465696957 : FREE
/showname/16467419944 : Mybitwave.com UK
/showname/16469181975 : FREE
/showname/21501350 : SecureSurf.EU NO
/showname/21501351 : FileCloud365 Norwegian
/showname/21501352 : FREE
/showname/21501353 : RadioPlantes Norwegian
';
$myRows= explode("\n", $test);
foreach( $myRows as $key => $value) {
$pieces = explode(":", $value);
$result[] = $pieces[1];
}
foreach ($result as $res){
$res // covert to php variable
//example: $RealCoffeeSweeden = 0;
}
You can try it this way
$my_array = explode("\n", $test);
foreach($my_array as $key => $value {
$my_string = explode(':', $value)
${str_replace(' ','', $my_string[1])} = $my_string;
echo $$my_string;
}
You should use an array for that. But if you want to do it the way you write, you can simply do something like that:
foreach( $myRows as $key => $value) {
$pieces = explode(":", $value);
$res = str_replace(' ', '', $pieces[1]); // replace whitespaces for valid names
$$res = 0; // note the double dollar signs
}
If you want to use an array tho, do something like this:
$result = [];
foreach( $myRows as $key => $value) {
$pieces = explode(":", $value);
$key = str_replace(' ', '', $pieces[1]);
$result[$key] = 0;
}
According to your comment, change second last line in the foreach loop with following:
$res = str_replace(' ', '', $res) . '_f';
Related
I need to broke a string into some vars but its order is not fixed as the exemple:
$string = "name='John';phone='555-5555';city='oakland';";
$string2 = "city='oakland';phone='555-5555';name='John';";
$string3 = "phone='555-5555';name='John';city='oakland';";
so I need to broke the strings into:
$name
$phone
$city
if the position would be fixed i could use explode and call for the array key that i need like
$brokenString = explode("'",$string);
$name = $brokenString[1];
$phone = $brokenString[3];
$city = $brokenString[5];
however how could I do it with variable position??
One way to do it with sort to make the position same always for all string variables.
<?php
$string = "name='John';phone='555-5555';city='oakland';";
$string2 = "city='oakland';phone='555-5555';name='John';";
$string3 = "phone='555-5555';name='John';city='oakland';";
$array = explode(';',$string3);
sort($array);
$array = array_filter($array); # remove the empty element
foreach($array as $value){
$split = explode('=',$value);
$result[$split[0]] = $split[1];
}
extract($result); # extract result as php variables
echo "\$city = $city; \$name = $name; \$phone = $phone";
?>
EDIT: As using extract() is generally not a good idea.You can use simple foreach() instead of extract(),
foreach($result as $k => $v) {
$$k = $v;
}
WORKING DEMO: https://3v4l.org/RB8pT
There might be a simpler method, but what I've done is created an array $stringVariables which holds the exploded strings.
This array is then looped through and strpos is used in each element in the exploded string array to see if it contains 'city', 'phone', or 'name'. Depending on which one, it's added to an array which holds either all the names, cities or phone numbers.
$stringVariables = array();
$phones = array();
$names = array();
$cities = array();
$stringVariables[] = explode(";",$string);
$stringVariables[] = explode(";",$string2);
$stringVariables[] = explode(";",$string3);
foreach($stringVariables as $stringVariable) {
foreach($stringVariable as $partOfString) {
if(strpos($partOfString, "name=") !== false) {
$names[] = $partOfString;
}else if(strpos($partOfString, "city=") !== false) {
$cities[] = $partOfString;
}else if(strpos($partOfString, "phone=") !== false) {
$phones[] = $partOfString;
}
}
}
An alternative way is to convert it into something that can be parsed as a URL string.
First part is to change the values and , from 'John', to John& using a regex ('([^']+)'; which looks for a ' up to a ' followed by a ;), then parse the result (using parse_str())...
$string = "name='John';phone='555-5555';city='oakland';";
$string = preg_replace("/'([^']+)';/","$1&", $string);
echo $string.PHP_EOL;
parse_str( $string, $values );
print_r($values);
gives the output of
name=John&phone=555-5555&city=oakland&
Array
(
[name] => John
[phone] => 555-5555
[city] => oakland
)
or just using regex's...
preg_match_all("/(\w*)?='([^']+)';/", $string, $matches);
print_r(array_combine($matches[1], $matches[2]));
I am working with my code, that can convert a query string into array.
This is my query string:
key1=['PH','PHILIPPINES']&key2=['KR','KOREA']
And I want only to display the second row, something like this:
Philippines
Korea
In my code, it's working but it displays:
['PH','PHILIPPINES']
['KR','KOREA
Here is my code:
<?php
$get_string = "key1=['PH','PHILIPPINES']&key2=['KR','KOREA']";
parse_str($get_string, $get_array);
$colors = $get_array;
foreach ($colors as $key => $value) {
echo $value."<BR>";
}
?>
This is your code:
<?php
$get_string = "key1=['PH','PHILIPPINES']&key2=['KR','KOREA']";
parse_str($get_string, $get_array);
$colors = $get_array;
foreach ($colors as $key => $value) {
// remove first and last characters ( "[" and "]" )
$value = substr($value, 1, -1);
// explode
$value = explode(",", $value);
// remove "'"
$our_value = str_replace("'", "", trim($value[1]));
// show
echo ucfirst(strtolower($our_value))."<BR>";
}
?>
I think you need this.
just simple explode by comma , and preg_replace to get only alphabates.
$get_string = "key1=['PH','PHILIPPINES']&key2=['KR','KOREA']";
parse_str($get_string, $get_array);
$colors = $get_array;
foreach ($colors as $key => $value) {
$x = explode(",",$value);
$new_string = preg_replace("/[^A-Za-z0-9?!]/",'',$x[1]);
echo $new_string."<br>";
}
Output :
PHILIPPINES
KOREA
$var = array(
'PH'=>'PHILLIPINES',
'KR'=>'KOREA');
Else
$var= array(
array('KR'=>'KOREA'),
array('PH'=>'PHILLIPINES')
);
Then echo in
foreach loop.
I really need some help with this code and I'm not that good at PHP.
Here is the code:
function projectAttr($number){
global $clerk, $project;
$projectid = $project['id'];
$tags = array();
$cleanUrls= (bool) $clerk->getSetting( "clean_urls", 1 );
$getTags = $clerk->query_select ( "projects_to_tags", "DISTINCT tag", "WHERE projectid='$projectid' ORDER BY id ASC" );
while ( $tag= $clerk->query_fetchArray( $getTags ) )
{
$tagset = explode('; ', $tag['tag']);
}
return html_entity_decode($tagset[$number]);
}
The code explodes a string and puts it in a array, that I can get by projectAttr(0). But I want to be more specific in what I want to get from the string.
This is my string:
size='large'; caption='short text about post/project'; bgcolor='black'; color='white';
What I want is, if I write projectAttr(size) it should return the value large and so forth.
Is that even possible?
Thanks, Peter
I'll answer specifically to the explode you want. You should modify your projectAttr function to look this this:
$items = explode('; ', $string);
$attr = array();
foreach($items as $item) {
list($key, $val) = explode('=', $item);
$attr[$key] = str_replace(array("'", ""), '',$val);
}
Which returns
Array (
[size] => large
[caption] => short text about post/project
[bgcolor] => black
[color] => white
)
EXAMPLE DEMO
So modify your function to look like this:
function projectAttr($name) {
global $clerk, $project;
$projectid = $project['id'];
$tags = array();
$cleanUrls = (bool) $clerk->getSetting("clean_urls", 1);
$getTags = $clerk->query_select("projects_to_tags", "DISTINCT tag", "WHERE projectid='$projectid' ORDER BY id ASC");
while ($tag = $clerk->query_fetchArray($getTags)) {
$items = explode('; ', $string);
$attr = array();
foreach ($items as $item) {
list($key, $val) = explode('=', $item);
$attr[$key] = str_replace(array("'", ""), '', $val);
}
}
return html_entity_decode($attr[$name]);
}
And that should allow you to call it like this:
projectAttr('size');
try
function projectAttr($number){
$str= "size='large'; caption='short text about post/project'; bgcolor='black'; color='white';";
$r = explode('; ', $str);
foreach($r as $k=>$v) {
$attr = explode('=', $v);
$projectAttr[$attr[0]] = str_replace("'", "", $attr[1]);
}
return html_entity_decode($projectAttr[$number]);
}
echo projectAttr('size'); // large
I am working on a latin website that holds some information in a string this way:
nominative:0:us,a,um;genitive:0:i;dative,ablative:1:is
I would like to turn this information into an array like this
array(
'nominative'=>array(
0=>array('us','a','um')
),
'genitive'=>array(
0=>'i'
)
'dative'=>array(
1=>'is'
)
'ablative'=>array(
1=>'is'
)
)
My current code looks like this
//turn into array for each specification
$specs=explode(';',$specificities);
foreach($specs as $spec):
//turn each specification into a consecutive array
$parts=explode(':',$spec);
//turn multiple value into array
foreach($parts as &$value)
if(strpos($value,',')!==false)
$value=explode(',',$value);
//imbricate into one other
while(count($parts)!==1):
$val=array_pop($parts);
$key=array_pop($parts);
if(is_array($key)):
foreach($key as $k)
$parts[$k]=$val;
else:
$parts[$key]=$val;
endif;
endwhile;
endforeach;
I'm stuck. Help.
Edit: Thanks for the quick responses everybody!
The response I preferred was from CaCtus. I modified it to add flexibility but it was the most useful.
For those interested, here is the new code:
$parts=explode(';','nominative:0:er,ra,rum;genitive:0:i;dative,ablative:1:is;root:r;');
if(!empty($parts)&&!empty($parts[0])):
foreach($parts as $part):
$subpart=explode(':',$part);
$keys=explode(',',$subpart[0]);
foreach($keys as $key):
#$vals=(strpos($subpart[2],',')!==false)
?explode(',',$subpart[2])
:$subpart[2];
$final=(is_null($vals))
?$subpart[1]
:array($subpart[1]=>$vals);
endforeach;
endforeach;
endif;
$string = 'nominative:0:us,a,um;genitive:0:i;dative,ablative:1:is';
$finalArray = array();
// Separate each specification
$parts = explode(';', $string);
foreach($parts as $part) {
// Get values : specification name, index and value
$subpart = explode(':', $part);
// Get different specification names
$keys = explode(',', $subpart[0]);
foreach($keys as $key) {
if (preg_match('#,#', $subpart[2])) {
// Several values
$finalValues = explode(',', $subpart[2]);
} else {
// Only one value
$finalValues = $subpart[2];
}
$finalArray[$key] = array(
$subpart[1] => $finalValues
);
}
}
Would something a little simplier work?
function multiexplode ($delimiters,$string) {
$ready = str_replace($delimiters, $delimiters[0], $string);
$launch = explode($delimiters[0], $ready);
return $launch; }
$input = "0:us,a,um;genitive:0:i;dative,ablative:1:is";
$exploded = multiexplode(array(",",":",";"),$input);
$test = array(
'nominative'=>array(0=>array($exploded[1],$exploded[2],$exploded[3])),
$exploded[4]=>array(0=>$exploded[6]),
$exploded[7]=>array(1=>$exploded[10]),
$exploded[8]=>array(1=>$exploded[10]) );
print_r($test);
Just another alternative:
$specificities = "nominative:0:us,a,um;genitive:0:i;dative,ablative:1:is";
$specificities = trim($specificities, ";") . ";"; //mandatory a trailing ;
$pattern = "/(?<types>[a-z\,]+):(?<ids>\d):(?<values>.*?);/";
preg_match_all($pattern, $specificities, $matches, PREG_SET_ORDER);
$result = array();
array_map(function($item) use (&$result)
{
$types = explode("," , $item['types']);
if(count($types) == 1)
{
$result[$item['types']] = array(
$item['ids'] => explode("," , $item['values'])
);
}
else
{
foreach ($types as $type)
{
$result[$type] = array(
$item['ids'] => explode("," , $item['values'])
);
}
}
}, $matches);
var_dump($result);
So i have a SQL call that grabs a set of tags and seperates them by commas with implode and explode but for the link area I would like to use the slug i saved in the db instead of the direct value.
$cg;
$tag=$mysqli->query("SELECT * FROM wp_pod_tbl_tags");
while($tags = $tag->fetch_object()){
$ct = explode(",", $categories);
foreach($ct as $c) {
if($tags->id == $c) {
$cg[] = $tags->name;
}
}
}
$arrs = implode(", ", $cg);
$arr = explode(",", $arrs);
$links = array();.0
foreach ($arr as $value) {
$links[] = "<a href='#". trim($value) ."'>". trim($value) ."</a>";
}
$links_str = implode(",", $links);
?>
<span><?=$links_str?></span>
Currently it comes out with Beer Garden. But can't figure out how to add it. To call it would be $tags->slug.
To get from this beer-garden to this Beer Garden you need to manipulate the string in two ways:
$value = 'beer-garden';
$value = str_replace('-',' ',$value);
$value = ucwords($value);
echo $value; // Beer Garden
You will have to adapt it to your situation, on the surface, there may be cases where this doesn't work. Especially when the name is suppose to have a dash.