I have this function which I expected to work well for converting strings to floats:
function getFloat($value) {
$cleanString = preg_replace('/([^0-9\.,])/i', '', $value);
$onlyNumbersString = preg_replace('/([^0-9])/i', '', $value);
$separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1;
$stringWithCommaOrDot = preg_replace('/([,\.])/', '', $cleanString, $separatorsCountToBeErased);
$removedThousendSeparator = preg_replace('/(\.|,)(?=[0-9]{3,}$)/', '', $stringWithCommaOrDot);
return (float) str_replace(',', '.', $removedThousendSeparator);
}
However:
$str = '449.0000';
echo getFloat($str);
// => 4490000
So I tried:
$str = '449.0000';
echo filter_var($str, FILTER_SANITIZE_NUMBER_FLOAT );
// => 4490000
Why does to they both convert 449.0000 to 449000?
The only thing that works here is (float) $str which returns 449 as expected but I need that function to get rid of alphabets spaces etc.
I like to use FILTER_VALIDATE_FLOAT
<?php
$str = '449.0000';
$filter = filter_var($str,FILTER_VALIDATE_FLOAT);
var_dump($filter);
if ($filter !== false) {
$float = floatval($filter);
var_dump($float);
}
Related
I am trying to extract relative keywords from description input which use Wysiwyg, with multi language english/arabic… using the following function but its not doing the task I want. Have a look the function I am using:
function extractKeyWords($string) {
mb_internal_encoding('UTF-8');
$stopwords = array();
$string = preg_replace('/[\pP]/u', '', trim(preg_replace('/\s\s+/iu', '', mb_strtolower($string))));
$matchWords = array_filter(explode(' ',$string) , function ($item) use ($stopwords) { return !($item == '' || in_array($item, $stopwords)
|| mb_strlen($item) <= 2 || is_numeric($item));});
$wordCountArr = array_count_values($matchWords);
// <p><p>
arsort($wordCountArr);
return array_keys(array_slice($wordCountArr, 0, 10)); }
figured it out ! Thanks
function generateKeywords($str)
{
$min_word_length = 3;
$avoid = ['the','to','i','am','is','are','he','she','a','an','and','here','there','can','could','were','has','have','had','been','welcome','of','home',' ','“','words','into','this','there'];
$strip_arr = ["," ,"." ,";" ,":", "\"", "'", "“","”","(",")", "!","?"];
$str_clean = str_replace( $strip_arr, "", $str);
$str_arr = explode(' ', $str_clean);
$clean_arr = [];
foreach($str_arr as $word)
{
if(strlen($word) > $min_word_length)
{
$word = strtolower($word);
if(!in_array($word, $avoid)) {
$clean_arr[] = $word;
}
}
}
return implode(',', $clean_arr);
}
This one seems very nice and comprehensive https://www.beliefmedia.com.au/create-keywords
Just make sure to change this line
$string = preg_replace('/[^\p{L}0-9 ]/', ' ', $string);
to
$string = preg_replace('/[^\p{L}0-9 ]/u', ' ', $string);
To support other langages (e.g Arabic)
And also better to use mb_strlen
If the string is in html format you can add the
strip_tags($str);
Before
$min_word_length = 3;
This question already has answers here:
PHP: Best way to extract text within parenthesis?
(8 answers)
Closed last year.
Input:
GUJARAT (24)
Expected Output:
24
String Format:
State Name (State Code)
How can I remove State Code with parentheses?
You can also use php explode:
$state = "GUJARAT (24)";
$output = explode( "(", $state );
echo trim( $output[0] ); // GUJARAT
$str = "GUJARAT (24)";
echo '<br />1.';
print_r(sscanf($str, "%s (%d)"));
echo '<br />2.';
print_r(preg_split('/[\(]+/', rtrim($str, ')')));
echo '<br />3.';
echo substr($str, strpos($str, '(')+1, strpos($str, ')')-strpos($str, '(')-1);
echo '<br />4.';
echo strrev(strstr(strrev(strstr($str, ')', true)), '(', true));
echo '<br />5.';
echo preg_replace('/(\w+)\s+\((\d+)\)/', "$2", $str);
If you know the stateCode length, and it is fixed
$state = "GUJARAT (24)";
$state = substr($state, strpos($state, "(") + 1, 2);
// get string upto "(", and remove right white space
echo $state;
You can check more about substr and strpos in php manual.
If stateCode length is not fixed, you can use regular expression:-
$state = 'GUJARAT (124)';
preg_match('/(\d+)/', $state, $res);
$stateCode = $res[0];
var_dump($stateCode);
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$fullstring = 'this is my [tag]dog[/tag]';
$parsed = get_string_between($fullstring, '[tag]', '[/tag]');
echo $parsed; // (result = dog)
you can use the function preg_match
$state = 'GUJARAT (24)'
$result = [];
preg_match('/[\(][\d]+[\)]/', $state, $result);
$stateCode = $result[0] // (24)
$stateCode = substr($stateCode, 1, strlen($stateCode) - 2); // will output 24
I have searched a lot of sites and SO answers for replacing characters in strings, but I didn't find a solution.
I need to replace only the last used character 'é' of a string.
It should work for every string, also if the string only contains once character 'é'.
code
echo strtr (strrchr ( 'accélérer','é' ), array ('é' => 'è')); // output èrer
echo str_replace("é","è",strrchr ( 'accélérer','é' )); // output èrer
desired results
accélérer -> accélèrer
sécher-> sècher
Have created custom function. Might be useful:
<?php
$str = 'accélérer';
$output = replaceMultiByte($str, 'é', 'è');
echo "OUTPUT=".$output; // accélèrer
echo '<br/><br/>';
$str = 'sécher';
$output = replaceMultiByte($str, 'é', 'è');
echo "OUTPUT=".$output; // sècher
function replaceMultiByte($str, $replace, $replaceWith)
{
$exp = explode($replace, $str);
$i = 1;
$cnt = count($exp);
$format_str = '';
foreach($exp as $v)
{
if($i == 1)
{
$format_str = $v;
}
else if($i == $cnt)
{
$format_str .= $replaceWith . $v;
}
else
{
$format_str .= $replace . $v;
}
$i++;
}
return $format_str;
}
?>
You could do something like this:
$str = 'accélérer';
$pos = strrpos( $str, 'é' );
if( $pos !== FALSE ) $str[$pos] = 'è';
Mat's answer did not work on me, so I work on more and I found è is 2 btye in strlen and 1 byte in mb_strlen. So in order to work with substr_replace
$str = "accélérer";
$pos = mb_strrpos($str, "é", "UTF-8");
if ($pos !== false) {
$str = substr_replace($str, "è", $pos + 1, strlen("è") );
}
var_dump($str); // string(11) "accélèrer"
How to convert this 19,500 string to number. If I do this
<?php
$val = "19,500";
$number = explode("," , $val);
$newnumber = $number[0].$number[1];
?>
But I don't think this is correct way.
LIVE DEMO
You can replace the string ',' to '' and then convert into integer by int
<?php
$number = "19,500";
$updatedNumber = str_replace(',','',$number);
echo (int)$updatedNumber ;
NOTE: int is better to use than intval function.
It reduces overhead of calling the function in terms of Speed.
http://objectmix.com/php/493962-intval-vs-int.html
Try this:
<?php
$val = "19,500";
$val = str_replace(',', '.', $val);
$number = (float)$val;
?>
UPDATED:
if comma comes out as a thousands-separator then:
<?php
$val = "19,500";
$val = str_replace(',', '', $val);
$number = (int)$val;
?>
you can simply replace ',' with ''
$newnumber = str_replace(',', '', $val);
the best way is:
<?php
$val = "19,500";
$tmp = str_replace(',', '', $val);
$newnumber = (float)$tmp;
?>
I think you just want to remove the ,:
<?php
$val = "19,500";
$val = strtr($val, array(',' => ''));
$number = intval($val);
var_dump($number);
use strtr() instead of str_replace() in case of multiple ,
When I see your code it's just sting string(5) "19500"
<?php
$val = "19,500";
$number = explode("," , $val);
$newnumber = $number[0].$number[1];
var_dump($newnumber);
?>
so you can convert to integer like the following
<?php
$val = "19,500";
$number = explode("," , $val);
$newnumber = $number[0].$number[1];
$realinteger = (int)($newnumber);
var_dump($realinteger);
?>
So the result will be int(19500)
Just try this code
$val = "19,500";
$newnumber = intval(str_replace(',', '', str_replace('.', '', $val))); // output : 19500
$val = "19,500.25";
$newnumber = intval(str_replace(',', '', str_replace('.', '', $val))); // output : 1950025
you can edit delimiter that want to replace with balnk string :)
Or you can try this
$newnumber = preg_match("/[^0-9,. -]/", $val) ? 0 : preg_replace("/[^0-9.-]/", "",$val);
just try one. simple as that :)
<?php
$val = "19,500";
$val = str_replace(',','', $val);
$newnumber = number_format($val,2);
?>
OUTPUT:
19,500.00
If you want to have no decimal you can change the 2 in 0. Like this.
OUTPUT:
19,500
i want : He had XXX to have had it. Or : He had had to have XXX it.
$string = "He had had to have had it.";
echo preg_replace('/had/', 'XXX', $string, 1);
output :
He XXX had to have had it.
in the case of, 'had' is replaced is the first.
I want to use the second and third. not reading from the right or left, what "preg_replace" can do it ?
$string = "He had had to have had it.";
$replace = 'XXX';
$counter = 0; // Initialise counter
$entry = 2; // The "found" occurrence to replace (starting from 1)
echo preg_replace_callback(
'/had/',
function ($matches) use ($replace, &$counter, $entry) {
return (++$counter == $entry) ? $replace : $matches[0];
},
$string
);
Try this:
<?php
function my_replace($srch, $replace, $subject, $skip=1){
$subject = explode($srch, $subject.' ', $skip+1);
$subject[$skip] = str_replace($srch, $replace, $subject[$skip]);
while (($tmp = array_pop($subject)) == '');
$subject[]=$tmp;
return implode($srch, $subject);
}
$test ="He had had to have had it.";;
echo my_replace('had', 'xxx', $test);
echo "<br />\n";
echo my_replace('had', 'xxx', $test, 2);
?>
Look at CodeFiddle
Probably not going to win any concours d'elegance with this, but very short:
$string = "He had had to have had it.";
echo strrev(preg_replace('/dah/', 'XXX', strrev($string), 1));
Try this
Solution
function generate_patterns($string, $find, $replace) {
// Make single statement
// Replace whitespace characters with a single space
$string = preg_replace('/\s+/', ' ', $string);
// Count no of patterns
$count = substr_count($string, $find);
// Array of result patterns
$solutionArray = array();
// Require for substr_replace
$findLength = strlen($find);
// Hold index for next replacement
$lastIndex = -1;
// Generate all patterns
for ( $i = 0; $i < $count ; $i++ ) {
// Find next word index
$lastIndex = strpos($string, $find, $lastIndex+1);
array_push( $solutionArray , substr_replace($string, $replace, $lastIndex, $findLength));
}
return $solutionArray;
}
$string = "He had had to have had it.";
$find = "had";
$replace = "yz";
$solutionArray = generate_patterns($string, $find, $replace);
print_r ($solutionArray);
Output :
Array
(
[0] => He yz had to have had it.
[1] => He had yz to have had it.
[2] => He had had to have yz it.
)
I manage this code try to optimize it.