I have this string:
525,294,475,215,365,745
and i need to remove 475..and comma.
and if i need to remove first number i need to remove also the next comma, also for last.
I can i do?
a regular expression?
thx
$newStr = str_replace(',475', '525,294,475,215,365,745');
Or the less error prone way:
$new = array();
$pieces = explode(',', '525,294,475,215,365,745');
foreach ($pieces as $piece) {
if ($piece != 475) {
$new[] = $piece;
}
}
$newStr = implode(',', $new);
Here's a regular expression:
$s = "525,294,475,215,365,745";
$s = preg_replace(',?475', '', $s);
$data = "525,294,475,215,365,745";
$parts = explode(',', $data);
for ($i = 0; $i < count($parts); $i++) {
if ($parts[$i] == 475) {
unset($parts[$i]);
}
}
$newdata = join(',', $parts);
<?php
$bigString = "525,294,475,215,365,745";
$pos = strpos($bigString, ",");
while($pos != false) {
$newString .= substr($bigString, 0, $pos);
$bigString = substr($bigString, $pos + 1);
$pos = strpos($bigString, ",");
}
echo $newString;
?>
function filterValue($index, &$a)
{
$key = array_search($index, $a);
if ($key != false) {
unset($a[$key]);
}
}
// Original data
$data = "525,294,475,215,365,745";
$data = explode(',', $data);
filterValue('475', $data);
$output = implode(',', $data);
Related
I have an array of words. e.g.,
$pattern = ['in', 'do', 'mie', 'indo'];
I wanna split a words match by the patterns to some ways.
input =
indomie
to output =
$ in, do, mie
$ indo, mie
any suggests?
*ps sorry for bad english. thank you very much!
it was an very interesting question.
Input:-
$inputSting = "indomie";
$pattern = ['in', 'do', 'mie', 'indo','dom','ie','indomi','e'];
Output:-
in,do,mie
in,dom,ie
indo,mie
indomi,e
Approach to this challenge
Get the pattern string length
Get the all the possible combination of matrix
Check whether the pattern matching.
if i understand your question correctly then above #V. Prince answer will work only for finding max two pattern.
function sampling($chars, $size, $combinations = array()) {
if (empty($combinations)) {
$combinations = $chars;
}
if ($size == 1) {
return $combinations;
}
$new_combinations = array();
foreach ($combinations as $combination) {
foreach ($chars as $char) {
$new_combinations[] = $combination . $char;
}
}
return sampling($chars, $size - 1, $new_combinations);
}
function splitbyPattern($inputSting, $pattern)
{
$patternLength= array();
// Get the each pattern string Length
foreach ($pattern as $length) {
if (!in_array(strlen($length), $patternLength))
{
array_push($patternLength,strlen($length));
}
}
// Get all the matrix combination of pattern string length to check the probablbe match
$combination = sampling($patternLength, count($patternLength));
$MatchOutput=Array();
foreach ($combination as $comp) {
$intlen=0;
$MatchNotfound = true;
$value="";
// Loop Through the each probable combination
foreach (str_split($comp,1) as $length) {
if($intlen<=strlen($inputSting))
{
// Check whether the pattern existing
if(in_array(substr($inputSting,$intlen,$length),$pattern))
{
$value = $value.substr($inputSting,$intlen,$length).',';
}
else
{
$MatchNotfound = false;
break;
}
}
else
{
break;
}
$intlen = $intlen+$length;
}
if($MatchNotfound)
{
array_push($MatchOutput,substr($value,0,strlen($value)-1));
}
}
return array_unique($MatchOutput);
}
$inputSting = "indomie";
$pattern = ['in', 'do', 'mie', 'indo','dom','ie','indomi','e'];
$output = splitbyPattern($inputSting,$pattern);
foreach($output as $out)
{
echo $out."<br>";
}
?>
try this one..
and if this solves your concern. try to understand it.
Goodluck.
<?php
function splitString( $pattern, $string ){
$finalResult = $semiResult = $output = array();
$cnt = 0;
# first loop of patterns
foreach( $pattern as $key => $value ){
$cnt++;
if( strpos( $string, $value ) !== false ){
if( implode("",$output) != $string ){
$output[] = $value;
if( $cnt == count($pattern) ) $semiResult[] = implode( ",", $output );
}else{
$semiResult[] = implode( ",", $output );
$output = array();
$output[] = $value;
if( implode("",$output) != $string ){
$semiResult[] = implode( ",", $output );
}
}
}
}
# second loop of patterns
foreach( $semiResult as $key => $value ){
$stackString = explode(",", $value);
/* if value is not yet equal to given string loop the pattern again */
if( str_replace(",", "", $value) != $string ){
foreach( $pattern as $key => $value ){
if( !strpos(' '.implode("", $stackString), $value) ){
$stackString[] = $value;
}
}
if( implode("", $stackString) == $string ) $finalResult[] = implode(",", $stackString); # if result equal to given string
}else{
$finalResult[] = $value; # if value is already equal to given string
}
}
return $finalResult;
}
$pattern = array('in','do','mie','indo','mi','e', 'i');
$string = 'indomie';
var_dump( '<pre>',splitString( $pattern, $string ) );
?>
My string is : Hi my, name is abc
I would like to output "Hi Name".
[Basically first word of comma separated sentences].
However sometimes my sentence can also be Hi my, "name is, abc"
[If the sentence itself has a comma then the sentence is enclosed with ""].
My output in this case should also be "Hi Name".
So Far I've done this
$str = "hi my,name is abc";
$result = explode(',',$str); //parsing with , as delimiter
foreach ($result as $results) {
$x = explode(' ',$results); // parsing with " " as delimiter
forach($x as $y){}
}
You can use explode to achieve YOUR RESULT and for IGINORE ' OR " use trim
$str = 'hi my,"name is abc"';
$result = explode(',',$str); //parsing with , as delimiter
$first = explode(' ',$result[0]);
$first = $first[0];
$second = explode(' ',$result[1]);
$second = trim($second[0],"'\"");
$op = $first." ".$second;
echo ucwords($op);
EDIT or if you want it for all , separated values use foreach
$str = 'hi my,"name is abc"';
$result = explode(',',$str); //parsing with , as delimiter
$op = "";
foreach($result as $value)
{
$tmp = explode(' ',$value);
$op .= trim($tmp[0],"'\"")." ";
}
$op = rtrim($op);
echo ucwords($op);
Basically it's hard to resolve this issue using explode, str_pos, etc. In this case you should use state machine approach.
<?php
function getFirstWords($str)
{
$state = '';
$parts = [];
$buf = '';
for ($i = 0; $i < strlen($str); $i++) {
$char = $str[$i];
if ($char == '"') {
$state = $state == '' ? '"' : '';
continue;
}
if ($state == '' && $char == ',') {
$_ = explode(' ', trim($buf));
$parts[] = ucfirst(reset($_));
$buf = '';
continue;
}
$buf .= $char;
}
if ($buf != '') {
$_ = explode(' ', trim($buf));
$parts[] = ucfirst(reset($_));
}
return implode(' ', $parts);
}
foreach (['Hi my, "name is, abc"', 'Hi my, name is abc'] as $str) {
echo getFirstWords($str), PHP_EOL;
}
It will output Hi Name twice
Demo
I have a comma separated string like
$str = "word1,word2,word3";
And i want to make a parent child relationship array from it.
Here is an example:
Try this simply making own function as
$str = "word1,word2,word3";
$res = [];
function makeNested($arr) {
if(count($arr)<2)
return $arr;
$key = array_shift($arr);
return array($key => makeNested($arr));
}
print_r(makeNested(explode(',', $str)));
Demo
function tooLazyToCode($string)
{
$structure = null;
foreach (array_reverse(explode(',', $string)) as $part) {
$structure = ($structure == null) ? $part : array($part => $structure);
}
return $structure;
}
Please check below code it will take half of the time of the above answers:
<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
if($prev != $i){
$result = array($arr[$i] => $result);
} else {
$result = array ($arr[$i]);
}
$prev = $i;
}
echo '<pre>',print_r($result),'</pre>';
Here is another code for you, it will give you result as you have asked :
<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
if($prev != $i){
if($i == 0){
$result = array($arr[$i] => $result);
}else{
$result = array(array($arr[$i] => $result));
}
} else {
$result = array ($arr[$i]);
}
$prev = $i;
}
echo '<pre>',print_r($result),'</pre>';
I have a string
$str = '1,2,3,4,5,"6,000",7,8,9';
How can I clean it up to:
'1,2,3,4,5,6000,7,8,9'
http://php.net/str-getcsv
$items = str_getcsv($str);
$items = array_map (
function ($item) { str_replace(',', '', $item); },
$items;
);
Now if you like you can merge them together again
$str = implode(',', $items);
Try something like this (for PHP < 5.3):
$dst = array();
$str = '1,2,3,4,5,"6,000",7,8,9';
$state = false;
$buffer = '';
for ($i = 0, $lim = strlen($str); $i < $lim; $i += 1) {
$char = $str[$i];
switch ($char) {
case ',':
if (!$state) {
$dst[] = $buffer;
$buffer = '';
}
break;
case '"':
$state = !$state;
break;
default:
$buffer .= $char;
}
}
$dst[] = $buffer;
print_r($dst);
Use this:
$str = '1,2,3,4,5,"6,000",7,8,9';
$pattern='/"(\d+),(\d+)"/';
$replacement='${1}$2';
echo preg_replace($pattern, $replacement, $str );
Thanks:-)
<?php
$str = '1,2,3,4,5,"6,000",7,8,9';
echo $str;
echo str_replace('"','',$str);
?>
I have list of brands and want to provide a search function with highlighting. For example, there are the following brands
Apple
Cewe Color
L'Oréal
Microsoft
McDonald's
Tom Tailor
The user then types lor in search form. I'm using the following snippet for searching
class search {
private function simplify($str) {
return str_replace(array('&',' ',',','.','?','|','\'','"'), '', iconv('UTF-8', 'ASCII//TRANSLIT', $str));
}
public function do_search($search) {
$search = self::simplify($search);
$found = array();
foreach (self::$_brands as $brand) {
if (mb_strstr(self::simplify($brand['name']), $search) !== false) $found[]= $brand;
}
return $found;
}
}
That gives me:
Cewe Color
L'Oréal
Tom Tailor
How would be a highlighting possible? Like:
Cewe Co<b>lor</b>
L'<b>Oré</b>al
Tom Tai<b>lor</b>
Btw: I know, that most things can be done with str_replace(), but that fit my needs not in all cases
$highlighted = str_replace($search, "<b>$search</b>", $brand);
would be the simplest method.
:)
Works with FedEx also ;)
$_brands = array
(
"Apple",
"Cewe Color",
"L'Oréal",
"Microsoft",
"McDonald's",
"Tom Tailor"
);
$q = 'lor';
$search = clean($q);
foreach($_brands as $key => $brand){
$brand = clean($brand);
$x = stripos($brand, $search);
if($x !== false){
$regexp = NULL;
$l = strlen($q);
for($i = 0; $i < $l; $i++){
$regexp .= mb_strtoupper($q[$i]).'.?';
}
$regexp = substr($regexp, 0, strlen($regexp) - 2);
$new = $_brands[$key];
$new = preg_replace('#('.$regexp.')#ui', '<b>$0</b>', $new);
echo $new."<br />";
}
}
function clean($string){
$string = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $string);
$string = preg_replace('#[^\w]#ui', '', $string);
return $string;
}
self::$_brands contains result from database (containing columns name, name_lower, name_translit, name_simplified)
class search {
private function translit($str) {
return iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', str_replace(array('ä', 'ü', 'ö', 'ß'), array('a', 'u', 'o', 's'), mb_strtolower($str)));
}
private function simplify($str) {
return preg_replace('/([^a-z0-9])/ui', '', self::translit($str));
}
public function do_search($simplified) {
$found = array();
foreach (self::$_brands as $brand) {
if (mb_strstr($brand['name_simplified'], $simplified) !== false) $found[]= $brand;
}
return $found;
}
private function actionDefault() {
$search = $_POST['search_fld'];
$simplified = self::simplify($search);
$result = self::do_search($simplified);
$brands = array();
foreach ($result as $brand) {
$hl_start = mb_strpos($brand['name_simplified'], $simplified);
$hl_len = mb_strlen($simplified);
$brand_len = mb_strlen($brand['name']);
$tmp = '';
$cnt_extra = 0;
$start_tag = false;
$end_tag = false;
for ($i = 0; $i < $brand_len; $i++) {
if (($i - $cnt_extra) < mb_strlen($brand['name_simplified']) && mb_substr($brand['name_translit'], $i, 1) != mb_substr($brand['name_simplified'], $i - $cnt_extra, 1)) $cnt_extra++;
if (($i - $cnt_extra) == $hl_start && !$start_tag) {
$tmp .= '<b>';
$start_tag = true;
}
$tmp .= mb_substr($brand['name'], $i, 1);
if (($i - $cnt_extra + 1) == ($hl_start + $hl_len) && !$end_tag) {
$tmp .= '</b>';
$end_tag = true;
}
}
if ($start_tag && !$end_tag) $tmp .= '</b>';
$brands[] = "" . $tmp . "";
}
echo implode(' | ', $brands);
}
}