$variable = "test_company_insurance_llc_chennai_limited_w-8tyu.pdf";
I need to display above the $variable like
Test Company Insurance LLC Chennai Limited W-8TYU.pdf
For that I've done:
$variable = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$test = explode(" ", $variable);
$countof = count($test);
for ($x=0; $x<$countof; $x++) {
if($test[$x] == 'w-8tyu' || $test[$x] == 'llc') {
$test[$x] = strtoupper($test[$x]);
//todo
}
}
I've got stuck in the to-do part.
I will change the specific words to uppercase using strtoupper.
Later, how should I need to merge the array?
Any help will be thankful...
$str_in = "test_company_insurance_llc_chennai_limited_w-8tyu.pdf";
$lst_in = explode("_", $str_in);
$lst_out = array();
foreach ($lst_in as $val) {
switch($val) {
case "llc" : $lst_out[] = strtoupper($val);
break;
case "w-8tyu.pdf" : $lst_temp = explode('.', $val);
$lst_out[] = strtoupper($lst_temp[0]) . "." . $lst_temp[1];
break;
default : $lst_out[] = ucfirst($val);
}
}
$str_out = implode(' ', $lst_out);
echo $str_out;
Not terribly elegant, but perhaps slightly more flexible.
$v = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$acronyms = array('llc', 'w-8tyu');
$ignores = array('pdf');
$v = preg_replace_callback('/(?:[^\._\s]+)/', function ($match) use ($acronyms, $ignores) {
if (in_array($match[0], $ignores)) {
return $match[0];
}
return in_array($match[0], $acronyms) ? strtoupper($match[0]) : ucfirst($match[0]);
}, $v);
echo $v;
The ignores can be removed provided you separate the extension from the initial value.
See the code below. I have printed the output of the code as your expected one. So Run it and reply me...
$variable = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$test = explode(" ", $variable);
$countof = count($test);
for ($x=0; $x<$countof; $x++) {
if($test[$x] == 'llc') {
$test[$x] = strtoupper($test[$x]);
//todo
}elseif($test[$x] == 'w-8tyu.pdf'){
$file=basename($test[$x],'pdf');
$info = new SplFileInfo($test[$x]);
$test[$x] = strtoupper($file).$info->getExtension();
}
else{
$test[$x]=ucfirst($test[$x]);
}
}
echo '<pre>';
print_r($test);
echo '</pre>';
echo $output = implode(" ", $test);
Related
I have to check a array of string data .
For example this is the string :
$keywords="today, tomorroy, world, is a good day , a good day is, today"
I have to check if is single word or multi word.
If is multi word i have to order and leave only one for example : is a good day ; a good day is i have to leave only : is a good day . This words i have to store in other array.
In the end i have to have only this results:
This is my code:
$keywords = "";
$singleword="";
$multiword="";
foreach ($response->getResults() as $result) {
$keywords .= $result->getText()->getValue() . ",";
if(count(explode(' ', $keywords)) > 1) {
$multiword++;
}
$singleword++;
}
return $keywordsgenerated;
I need to return : today, tomorroy, world, is a good day
Please can you help me to fix , i'm new in php.
EDIT
I think you were looking for something like this:
<?php
$keywords="today, tomorrow, world, is a good day , a good day is, today";
$arr = array_unique(explode(",",$keywords));
$words = [];
foreach($arr as $key=>$a) {
$words_explode = explode(" ", $a);
foreach($words_explode as $w) {
$words[] = $w;
}
}
$new_words = array_unique($words);
$result = implode(" ", $new_words);
foreach($arr as $item) {
$result = str_replace($item,$item.",",$result);
}
$result = trim($result,", ");
var_dump($result);
UPDATE:
I think? I got what you were looking for?
$keywords = "hansgrohe,hansgrohe focus,küchenarmatur,hansgrohe metris";
$arr = explode(',', $keywords);
$already = [];
$result = '';
foreach($arr as $word) {
$subword = explode(" ", $word);
foreach($subword as $actual_word) {
if (!in_array($actual_word, $already)) {
$result .= $actual_word . ' ';
$already[] = $actual_word;
}
}
}
$result = rtrim($result);
//would result in hansgrohe focus küchenarmatur metris
echo $result;
UPDATE2:
If you want to know number of occurences of each word.
<?php
$keywords = "hansgrohe,hansgrohe focus,küchenarmatur,hansgrohe metris";
$arr = explode(",", $keywords);
$already = [];
$nrwords = [];
$result = '';
foreach($arr as $word) {
$subword = explode(" ", $word);
foreach($subword as $actual_word) {
if (!in_array($actual_word, $already)) {
$result .= $actual_word . ' ';
$already[] = $actual_word;
$nrwords[$actual_word] = 0;
}
$nrwords[$actual_word]++;
}
}
$result = rtrim($result);
//would result in hansgrohe focus küchenarmatur metris
echo $result;
//would show how many of each word that exists
echo '<pre>';
print_r($nrwords);
echo '</pre>';
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 main array containing the following arrays
(at least 50 different types) :
I'm currently programming in php but i can probably adapt the same functions in java , c# etc...
array('type'=>'x-y','value'=>'12');
array('type'=>'y-z','value'=>'6');
array('type'=>'y-x','value'=>'56');
array('type'=>'z-x','value'=>'19');
array('type'=>'z-y','value'=>'18');
array('type'=>'x-z','value'=>'67');
........
I want to create and traverse a graph for each key and run operations on them e.g :
x-y-z-x : 12 * 6 * 19
x-y-x : 12 * 56
x-z-x : 67 * 19
y-z-y : 6 * 18
.......
I have been trying to run each independently using foreach loops but it won't work for the size of dataset that i have .
Any help would be greatly appreciated. Thanks
The code is in php as required, you can test it as well..
function initData($final, $paths, $values) {
for($i=0; $i<sizeof($final);$i++) {
$path = explode('-', $final[$i]["type"]);
$value = $final[$i]["value"];
array_push($paths, $path);
array_push($values, $value);
}
return [$paths, $values];
}
function getFinalValue($finalPath, $paths, $values) {
$path = explode('-', $finalPath);
$finalValue = 1;
for($i=0;$i<sizeof($path)-1;$i++) {
$stop = $path[$i+1];
$start = $path[$i];
$smallPath = array($start, $stop);
$finalValue *= getValue($smallPath, $paths, $values);
}
return $finalValue;
}
function getValue($smallPath, $paths, $values) {
$value = 0;
for($i=0; $i<sizeof($paths);$i++) {
if($smallPath[0] == $paths[$i][0])
{
if($smallPath[1] == $paths[$i][1]) {
print_r($smallPath);
echo ' ';
$value = $values[$i];
print_r($value);
echo '<br>';
}
}
}
return $value;
}
//Test
function test() {
$a = array('type'=>'x-y','value'=>'12');
$b = array('type'=>'y-z','value'=>'6');
$c = array('type'=>'y-x','value'=>'56');
$d = array('type'=>'z-x','value'=>'19');
$e = array('type'=>'z-y','value'=>'18');
$f = array('type'=>'x-z','value'=>'67');
$paths = [];
$values = [];
$testString = 'x-y-z';
$final = array($a,$b,$c,$d,$e,$f);
$data = initData($final, $paths, $values);
$paths = $data[0];
$values = $data[1];
for ($i=0;$i<sizeof($paths);$i++) {
print_r($paths[$i]);
print_r($values[$i]);
echo '<br>';
}
echo '<br>';
echo '<br>';
$finalValue = getFinalValue($testString, $paths, $values);
echo $testString . '=' . $finalValue;
}
test();
?>
I use php preg_match to match the first & last word in a variable with a given first & last specific words,
example:
$first_word = 't'; // I want to force 'this'
$last_word = 'ne'; // I want to force 'done'
$str = 'this function can be done';
if(preg_match('/^' . $first_word . '(.*)' . $last_word .'$/' , $str))
{
echo 'true';
}
But the problem is i want to force match the whole word at (starting & ending) not the first or last characters.
Using \b as boudary word limit in search:
$first_word = 't'; // I want to force 'this'
$last_word = 'ne'; // I want to force 'done'
$str = 'this function can be done';
if(preg_match('/^' . $first_word . '\b(.*)\b' . $last_word .'$/' , $str))
{
echo 'true';
}
I would go about this in a slightly different way:
$firstword = 't';
$lastword = 'ne';
$string = 'this function can be done';
$words = explode(' ', $string);
if (preg_match("/^{$firstword}/i", reset($words)) && preg_match("/{$lastword}$/i", end($words)))
{
echo 'true';
}
==========================================
Here's another way to achieve the same thing
$firstword = 'this';
$lastword = 'done';
$string = 'this can be done';
$words = explode(' ', $string);
if (reset($words) === $firstword && end($words) === $lastword)
{
echo 'true';
}
This is always going to echo true, because we know the firstword and lastword are correct, try changing them to something else and it will not echo true.
I wrote a function to get Start of sentence but it is not any regex in it.
You can write for end like this. I don't add function for the end because of its long...
<?php
function StartSearch($start, $sentence)
{
$data = explode(" ", $sentence);
$flag = false;
$ret = array();
foreach ($data as $val)
{
for($i = 0, $j = 0;$i < strlen($val), $j < strlen($start);$i++)
{
if ($i == 0 && $val{$i} != $start{$j})
break;
if ($flag && $val{$i} != $start{$j})
break;
if ($val{$i} == $start{$j})
{
$flag = true;
$j++;
}
}
if ($j == strlen($start))
{
$ret[] = $val;
}
}
return $ret;
}
print_r(StartSearch("th", $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);
}
}