There will be a string with a single or multiple with no commas at all.
$str = "a, b";
How do I get the first value before the comma if it contains comma(s)? This is what I did.
if(preg_match('/[,]+/', $str, $f)) {
$firstVal = $f[0];
}
NOTE: Is /^[^,]+/ better suited?
You can use strtok:
$firstVal = strtok($str, ",")
There are several ways to achieve this.
Using substr() and strpos()
echo substr($str,0,strrpos($str,','));
Using explode()
$result = explode(',',$str);
echo $result[0];
Using strstr()
echo strstr($str, ',', true);
Explode, validate and print.
$values = explode(',',$str);
if(key_exists(0,$values) && trim($values[0])!=""){
echo $values[0];
}
Related
I have this elements where I need to extract this {{search_tag}} and replace by a value
https://www.toto.com/search/10/{{search_tag}}.html#_his_
I tried this but I don't if it's the good way, does'nt work.
$words = explode('{{search_tag}} ',$website_url[$n]);
$exists_at = array_search($seach,$words);
if ($exists_at){
echo "Found at ".$exists_at." key in the \$word array";
}
You can use str_replace
$str = 'https://www.toto.com/search/10/{{search_tag}}.html#_his_';
$val = 'NEW_VALUE';
$new_str = str_replace("{{search_tag}}", $val, $str);
//outputs: https://www.toto.com/search/10/NEW_VALUE.html#_his_
I'm new to PHP and I have a problem.
I need delete all chars since a symbol (Sorry for my bad english , i'm from argentina)
I have this text :
3,94€
And I need the text is as follows:
3,94
I tried this by multiple ways but it didn't work.
There are a few ways you can do this:
Using strpos:
$string = '3,94€';
echo substr($string, 0, strpos($string, '&'));
or using strstr:
// Requires PHP 5.3+ due to the true (before_needle) parameter
$string = '3,94€';
echo strstr($string, '&', true);
or using explode:
// Useful if you need to keep the € part for later
$string = '3,94€';
list($part_a, $part_b) = explode('&', $string);
echo $part_a;
or using reset:
$string = '3,94€';
echo reset(explode('&', $string));
The best suited in your case would be to use strpos to find the first occurrence of & in the string, and then use substr to return the string from the begining until the value returned by strpos.
Another posibility is clean the number and then round it:
<?php
//Option 1: with regular expresions:
$val = '3,94€';
$res = preg_replace('/[^0-9.,]/','',$val);
var_dump($res);
//Option 2: with filter functions:
$res2 = filter_var($val, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
var_dump($res2);
//Output: 3,948364
//If you want to round it:
$res = substr($res, 0, 4);
var_dump($res);
?>
You can use regex: https://regex101.com/r/uY0kH3/1
It will work in preg_match() function.
You could use str_replace.
<?php
$string = 3,94€
$final = str_replace('€' ,'', $string);
echo $final;
How can I convert to uppercase for the following example :
title-title-title
Result should be:
Title-Title-Title
I tried with ucwords but it converts like this: Title-title-title
I currently have this:
echo $title = ($this->session->userdata('head_title') != '' ? $this->session->userdata('head_title'):'Our Home Page');
In this particular string example, you could explode the strings first, use that function ucfirst() and apply to all exploded strings, then put them back together again:
$string = 'title-title-title';
$strings = implode('-', array_map('ucfirst', explode('-', $string)));
echo $strings;
Should be fairly straightforward on applying this:
$title = '';
if($this->session->userdata('head_title') != '') {
$raw_title = $this->session->userdata('head_title'); // title-title-title
$title = implode('-', array_map('ucfirst', explode('-', $raw_title)));
} else {
$title = 'Our Home Page';
}
echo $title;
echo str_replace(" ","-",ucwords(str_replace("-"," ","title-title-title")));
Fiddle
Output:
Title-Title-Title
Demo
Not as swift as Ghost's but a touch more readable for beginners to see what's happening.
//break words on delimiter
$arr = explode("-", $string);
//capitalize first word only
$ord = array_map('ucfirst', $arr);
//rebuild the string
echo implode("-", $ord);
The array_map() applies callback to the elements of the given array. Internally, it traverses through the elements in our word-filled array $arr and applies the function ucfirst() to each of them. Saves you couple of lines.
Edit #2
This isn't working for the new information added to op, as there is an answer this won't be updated to reflect that.
Edit #1
$var = "title-title-title";
$var = str_replace (" ", "_", ucwords (str_replace (" ", "_", $var));
Old, non-working
$var = "title-title-title";
$var = implode("-", ucwords (explode("-", $var)));
try the following:
$str='title-title-title';
$s='';
foreach(explode('-',$str) as $si){
$s.= ($s ? "-":"").ucfirst($si);
}
$s should be Title-Title-Title at this point
So I have a list of values like that goes like this:
values: n,b,f,d,e,b,f,ff`
I want to use preg_replace() in order to remove the repeated characters from the list of values (it will be inserted to a MySQL table). b and f are repeated. ff should not count as f because it's a different value. I know that \b \b will be used for that. I am not sure on how to take out the repeated b and f values as well as the , that precedes each value.
If the list is in a string looking like the example above, a regex is overkill. This does it just as well;
$value = implode(',', array_unique(explode(',', $value)));
I agree with other commenters that preg_replace is not the way to go; but, since you ask, you can write:
$str = preg_replace('/\b(\w+),(?=.*\b\1\b)/', '', $str);
That will remove all but the last instance of a given list-element.
No need for regex for this:
join(",", array_unique(split(",", $values)))
If this list you're dealing with is a simple string, a possible solution would be like this:
function removeDuplicates($str) {
$arr = explode(',', $str);
$arr = array_unique($arr);
return implode(',', $arr);
}
$values = removeDuplicates('n,b,f,d,e,b,f,ff'); // n,b,f,d,e,ff
$str = "values: n,b,f,d,e,b,f,ff";
$arr = array();
preg_match("/(values: )([a-z,]+)/i", $str, $match);
$values = explode(",", $match[2]);
foreach($values AS $value){
if(!$arr[$value]) $arr[$value] = true;
}
$return = $match[1];
foreach($arr AS $a){
$return .= ($i++ >= 1 ? "," : "").$a;
}
Say this is my string
$string = 'product[0][1][0]';
How could I use that string alone to actually get the value from an array as if I had used this:
echo $array['product'][0][1][0]
I've messed around with preg_match_all with this regex (/\[([0-9]+)\]/), but I am unable to come up with something satisfactory.
Any ideas? Thanks in advance.
You could use preg_split to get the individual array indices, then a loop to apply those indices one by one. Here's an example using a crude /[][]+/ regex to split the string up wherever it finds one or more square brackets.
(Read the [][] construct as [\]\[], i.e. a character class that matches right or left square brackets. The backslashes are optional.)
function getvalue($array, $string)
{
$indices = preg_split('/[][]+/', $string, -1, PREG_SPLIT_NO_EMPTY);
foreach ($indices as $index)
$array = $array[$index];
return $array;
}
This is prettttty hacky, but this will work. Don't know how much your array structure is going to change, either, this won't work if you get too dynamic.
$array = array();
$array['product'][0][1][0] = "lol";
$string = 'product[0][1][0]';
$firstBrace = strpos( $string, "[" );
$arrayExp = substr($string, $firstBrace );
$key = substr( $string, 0, $firstBrace );
echo $arrayExp, "<br>";
echo $key, "<br>";
$exec = "\$val = \$array['".$key."']".$arrayExp.";";
eval($exec);
echo $val;
What about using eval()?
<?php
$product[0][1][0] = "test";
eval ("\$string = \$product[0][1][0];");
echo $string . "\n";
die();
?>