PHP string-manipulation - php

I have a string, for example:
"abc b, bcd vr, cd deb"
I would like to take the first word of this string until every single point in this case would result in "abc bcd cd". My code unfortunately does not work. Can you help me?
<?php
$string= "abc b, bcd vr, cd deb";
$ay = explode(",", $string);
$num= count($ay);
$ii= 0;
while ($ii!=$num){
$first = explode(" ", $ay[$ii]);
echo $first[$ii];
$ii= $ii+1;
}
?>

<?php
function get_first_word($string)
{
$words = explode(' ', $string);
return $words[0];
}
$string = 'abc b, bcd vr, cd deb';
$splitted = explode(', ', $string);
$new_splitted = array_map('get_first_word', $splitted);
var_dump($new_splitted);
?>

<?php
$string= "abc b, bcd vr, cd deb";
$ay = explode(",", $string);
$num= count($ay);
$ii= 0;
while ($ii!=$num){
$first = explode(" ", $ay[$ii]);
echo ($ii == 0) ? $first[0] . " " : $first[1] . " ";
$ii= $ii+1;
}
?>
You should only take $first[$ii] when you get first element becouse explode take this whan is before space at first element.

$string= "abc b, bcd vr, cd deb";
$ay = explode(",", $string);
foreach($ay as $words) {
$words = explode(' ', $words);
echo $words[0];
}

Using array_reduce():
$newString = array_reduce(
// split string on every ', '
explode(", ", $string),
// add the first word of every comma section to the partial string
function(&$result, $item){
$result .= array_shift(explode(" ", $item)) . " ";
return $result;
}
);

Related

PHP insert br tag after 2nd Word of a Given String

I'm trying to insert <br/> tag after 2nd word of a given string, but it crops some words of my string, can anyone help to fix the code on this
$pos = 1;
$string = 'Lorem Imsem Dollar Country';
$words = explode(" ", $string);
$new_array = array_slice($words, 0, $pos, true) +
array($pos => '<br/>') +
array_slice($words, $pos, count($words) - 1, true) ;
$new_string = join(" ",$new_array);
echo $new_string;
You can use array_splice :
$pos = 1;
$string = 'Lorem Imsem Dollar Country';
$words = explode(" ", $string);
array_splice( $words, $pos, 0, '<br>' );
$new_string = join(" ",$words);
echo $new_string;
With $pos you can select the position of the <br/> tag.
Use $pos = 2 to add the tag after second position
$pos = 2;
$string = 'Lorem Imsem Dollar Country';
$words = explode(" ", $string);
array_splice( $words, $pos, 0, '<br>' );
$new_string = join(" ",$words);
echo $new_string;
With preg_replace:
$new = preg_replace("/^(([^ ]+ ){2})/",'$1<br/>', $string);

How to precisely replace the string

$string = 'I am chan, my son is chan_junior';
$search = array('chan', 'chan_junior');
$replace = array('a', 'b');
$new = str_replace($search, $replace, $string);
echo $new;
I want to replace the string to I am a, my son is b, but the result is I am a, my son is a_junior. Is there a function to make it happen?
That happens because php search first for "chan", replace it on 2 places and then don't find second string. Search for longer strings first.
This works:
$string = 'I am chan, my son is chan_junior';
$search = array('chan', 'chan_junior');
$replace = array('a', 'b');
$str_arr = explode(' ', $string);
$count = count($str_arr);
for ($i = 0; $i < $count; $i ++)
{
$word = preg_replace('/^[^A-Za-z0-9\-]*|[^A-Za-z0-9\-]*$/', '', $str_arr[$i]);
if (in_array($word, $search))
{
$key = array_search($word, $search);
$str_arr[$i] = str_replace($word, $replace[$key], $str_arr[$i]);
}
}
$new = implode(' ', $str_arr);
echo $new;

replace all occurrences after nth occurrence php?

I have this string...
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|"
How do I replace all the occurrences of | with " " after the 8th occurrence of | from the beginning of the string?
I need it look like this, 1|2|1400|34|A|309|Frank|william|This is the line here
$find = "|";
$replace = " ";
I tried
$text = preg_replace(strrev("/$find/"),strrev($replace),strrev($text),8);
but its not working out so well. If you have an idea please help!
You can use:
$text = '1|2|1400|34|A|309|Frank|william|This|is|the|line|here|';
$repl = preg_replace('/^([^|]*\|){8}(*SKIP)(*F)|\|/', ' ', $text);
//=> 1|2|1400|34|A|309|Frank|william|This is the line here
RegEx Demo
Approach is to match and ignore first 8 occurrences of | using ^([^|]*\|){8}(*SKIP)(*F) and the replace each | by space.
You can use explode()
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$arr = explode('|', $text);
$result = '';
foreach($arr as $k=>$v){
if($k == 0) $result .= $v;
else $result .= ($k > 7) ? ' '.$v : '|'.$v;
}
echo $result;
You could use the below regex also and replace the matched | with a single space.
$text = '1|2|1400|34|A|309|Frank|william|This|is|the|line|here|';
$repl = preg_replace('~(?:^(?:[^|]*\|){8}|(?<!^)\G)[^|\n]*\K\|~', ' ', $text);
DEMO
<?php
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$texts = explode( "|", $text );
$new_text = '';
$total_words = count( $texts );
for ( $i = 0; $i < $total_words; $i++)
{
$new_text .= $texts[$i];
if ( $i <= 7 )
$new_text .= "|";
else
$new_text .= " ";
}
echo $new_text;
?>
The way to do that is:
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$arr = explode('|', $text, 9);
$arr[8] = strtr($arr[8], array('|'=>' '));
$result = implode('|', $arr);
echo $result;
Example without regex:
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$array = str_replace( '|', ' ', explode( '|', $text, 9 ) );
$text = implode( '|', $array );
str_replace:
If subject is an array, then the search and replace is performed with
every entry of subject, and the return value is an array as well.
explode:
If limit is set and positive, the returned array will contain a
maximum of limit elements with the last element containing the rest of
string.

Remove word from a string

I have a csv file that contains company names. I would want to match it against my database. In order to have a cleaner and nearer matches, I am thinking of eliminating some company suffixes like 'inc', ' inc', ', inc.' or ', inc'. Here's my sample code:
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc","inc."," Inc.",", Inc.",", Inc"," Inc");
foreach ($wordlist as &$word) {
$word = '/\b' . preg_quote($word, '/') . '\b/';
}
$string = preg_replace($wordlist, '', $string);
$foo = preg_replace('/\s+/', ' ', $string);
echo $foo;
My problem here is that the 'inc.' doesn't get removed. I'm guessing it has something to do with the preq_quote. But I just can't figure out how to solve this.
Try this :
$string = 'Inc incorporated inc.';
$wordlist = array("Inc","inc.");
foreach ($wordlist as $word) {
$string =str_replace($word, '', $string);
}
echo $string;
OR
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc","inc.");
$string = str_replace($wordlist, '', $string);
echo $string;
This will output as 'corporated'...
If you want "Incorporated" as result, make the "I" is small.. and than run my above code (first one)...
Try this. It may involve type juggling at some point, but will have your desired result
$string = 'Inc Incorporated inc.';
$wordlist = array('Inc', 'inc.');
$string_array = explode(' ', $string);
foreach($string_array as $k => $a) {
foreach($wordlist as $b) {
if($b == $a){
unset($string_array[$k]);
}
}
$string_array = implode('', $string_array);
You can use this
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc "," inc.");
$foo = str_replace($wordlist, '', $string);
echo $foo;
Run this code here
This will work for any number of elements in array...
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc");
foreach($wordlist as $stripped)
$string = preg_replace("/\b". preg_quote($stripped,'/') ."(\.|\b)/i", " ", $string) ;
$foo = preg_replace('/\s+/', ' ', $string);
echo $foo;

Php replace and concat

I need to replace and concat some values in a random string, i store the values in an array.
I.e.
$search = array('dog', 'tree', 'forest', 'grass');
$randomString = "A dog in a forest";
If one or more array values matches the random string then i need a replace like this:
$replacedString = "A #dog in a #forest";
Can someone help me?
Thx.
foreach (explode(' ', $randomString) as $word) {
$replacedString .= in_array($word, $search) ? "#$word " : "$word ";
}
echo $replacedString; // A #dog in a #forest
foreach($search as $word)
{
$randomString = str_replace($word,"#".$word,$randomString);
}
Not sure if I understand what you're trying to do correctly but have a look at str_replace() function
and try something like
foreach($search as $string)
{
$replacement[] = "#".$search;
}
$new_string = str_replace($search, $replacement, $randomString);
This should work for you:
$words = explode(" ", $randomString);
foreach($words as $word){
if(in_array($word, $search)){
$word = "#$word";
}
}
$replacedString = implode(" ", $words);

Categories