replace all occurrences after nth occurrence php? - 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.

Related

php search on string comma separated and get element that match

I have a question, if anyone can help me to solve this. I have a string separated by commas, and I want to find an item that partially matches:
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
I need to get only the full string from partial match as a result of filter:
$result = "GenomaPrintOrder";
With preg_match_all you can do like this.
Php Code
<?php
$subject = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView, NewPrintOrder";
$pattern = '/\b([^,]*PrintOrder[^,]*)\b/';
preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
echo "Matched: " . $val[1]. "\n";
}
?>
Output
Matched: GenomaPrintOrder
Matched: NewPrintOrder
Ideone Demo
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
$result = array();
$tmp = explode(",", $string);
foreach($tmp as $entrie){
if(strpos($entrie, $string) !== false)
$result[] = trim($entrie);
}
This will get you an array with all strings that match your search-string.
You can use regular expression to get the result:
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
$regex = '/([^,]*' . preg_quote($search, '/') . '[^,]*)/';
preg_match($regex, $string, $match);
$result = trim($match[1]); // $result == 'GenomaPrintOrder'
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
$array = explode(" ", $string);
echo array_filter($array, function($var) use ($search) { return preg_match("/\b$searchword\b/i", $var); });
Since there are so many different answers already, here is another:
$result = preg_grep("/$search/", explode(", ", $string));
print_r($result);

Edit all odd words in string to upper case

I need to edit all odd words to upper case.
Here is sample of imput string:
very long string with many words
Expected output:
VERY long STRING with MANY words
I have this code, but it seams to me, that I can do it in better way.
<?php
$lines = file($_FILES["fname"]["tmp_name"]);
$pattern = "/(\S[\w]*)/";
foreach($lines as $value)
{
$words = NULL;
$fin_str = NULL;
preg_match_all($pattern, $value, $matches);
for($i = 0; $i < count($matches[0]); $i = $i + 2){
$matches[0][$i] = strtoupper($matches[0][$i]);
$fin_str = implode(" ", $matches[0]);
}
echo $fin_str ."<br>";
P.S. I need to use only preg_match function.
Here's a preg_replace_callback example:
<?php
$str = 'very long string with many words';
$newStr = preg_replace_callback('/([^ ]+) +([^ ]+)/',
function($matches) {
return strtoupper($matches[1]) . ' ' . $matches[2];
}, $str);
print $newStr;
// VERY long STRING with MANY words
?>
You only need to match the repeating pattern: /([^ ]+) +([^ ]+)/, a pair of words, then preg_replace_callback recurses over the string until all possible matches are matched and replaced. preg_replace_callback is necessary to call the strtoupper function and pass the captured backreference to it.
Demo
If you have to use regular expressions, this should get you started:
$input = 'very long string with many words';
if (preg_match_all('/\s*(\S+)\s*(\S+)/', $input, $matches)) {
$words = array();
foreach ($matches[1] as $key => $odd) {
$even = isset($matches[2][$key]) ? $matches[2][$key] : null;
$words[] = strtoupper($odd);
if ($even) {
$words[] = $even;
}
}
echo implode(' ', $words);
}
This will output:
VERY long STRING with MANY words
You may don't need regex simply use explode and concatenate the string again:
<?php
function upperizeEvenWords($str){
$out = "";
$arr = explode(' ', $str);
for ($i = 0; $i < count($arr); $i++){
if (!($i%2)){
$out .= strtoupper($arr[$i])." ";
}
else{
$out .= $arr[$i]." ";
}
}
return trim($out);
}
$str = "very long string with many words";
echo upperizeEvenWords($str);
Checkout this DEMO

PHP - Convert a string with dashes while removing first word

$title = '228-example-of-the-title'
I need to convert the string to:
Example Of The Title
How would I do that?
A one-liner,
$title = '228-example-of-the-title';
ucwords(implode(' ', array_slice(explode('-', $title), 1)));
This splits the string on dashes (explode(token, input)),
minus the first element (array_slice(array, offset))
joins the resulting set back up with spaces (implode(glue, array)),
and finally capitalises each word (thanks salathe).
$title = '228-example-of-the-title'
$start_pos = strpos($title, '-');
$friendly_title = str_replace('-', ' ', substr($title, $start_pos + 1));
You can do this using the following code
$title = '228-example-of-the-title';
$parts = explode('-',$title);
array_shift($parts);
$title = implode(' ',$parts);
functions used: explode implode and array_shift
$pieces = explode("-", $title);
$result = "";
for ($i = 1; $i < count(pieces); $i++) {
$result = $result . ucFirst($pieces[$i]);
}
$toArray = explode("-",$title);
$cleanArray = array_shift($toArray);
$finalString = implode(' ' , $cleanArray);
// echo ucwords($finalStirng);
Use explode() to split the "-" and put the string in an array
$title_array = explode("-",$title);
$new_string = "";
for($i=1; $i<count($title_array); $i++)
{
$new_string .= $title_array[$i]." ";
}
echo $new_string;

PHP string find and replace until last instance

I have a string in a DB table which is separated by a comma i.e. this,is,the,first,sting
What I would like to do and don't know how is to have the string outputted like:
this, is, the, first and string
Note the spaces and the last comma is replaced by the word 'and'.
This can be your solution:
$str = 'this,is,the,first,string';
$str = str_replace(',', ', ', $str);
echo preg_replace('/(.*),/', '$1 and', $str);
First use, the function provided in this answer: PHP Replace last occurrence of a String in a String?
function str_lreplace($search, $replace, $subject)
{
$pos = strrpos($subject, $search);
if($pos === false)
{
return $subject;
}
else
{
return substr_replace($subject, $replace, $pos, strlen($search));
}
}
Then, you should perform a common str_replace on text to replace all other commas:
$string = str_lreplace(',', 'and ', $string);
str_replace(',',', ',$string);
$words = explode( ',', $string );
$output_string = '';
for( $x = 0; $x < count($words); x++ ){
if( $x == 0 ){
$output = $words[$x];
}else if( $x == (count($words) - 1) ){
$output .= ', and ' . $words[$x];
}else{
$output .= ', ' . $words[$x];
}
}

replace br tag from a string in php

I have the following string. I want to replace the line break with /n
Good FRIENDS are hard to find,<br
/> harder to leave,<br
/> and impossible to forget.
preg_replace("/<br\W*?\/>/", "\n", $your_string);
Have you tried str_replace?
str_replace("<br />", "\n", $your_string);
Use str_replace
$text = str_replace("<br />", "\n", $text);
If there is actually a line break within the <br /> tag as in your sample code, try this:
$text = preg_replace("/<br\n\W*\/>/", "\n", $text);
Use This function
function separate( $str,$subStr, $count )
{
$formatStr = '';
$start=0;
$num = 1;
while(!(strpos($str,$subStr,$start) === null))
{
$first = strpos($str,$subStr,$start);
if ($first < $start)
break;
$newStr = substr($str,$start,$first - $start + 1 );
$formatStr .= $newStr;
if ($num % $count == 0)
$formatStr .= '<br>';
$num ++;
$start = $first +1;
}
return $formatStr;
}
Example
$str = 'AAA.BBB.CCC.DDD.EEE.FFF.CCC';
echo separate ($str,'.', 3);
Output
AAA.BBB.CCC.
DDD.EEE.FFF.
You can also try below regex:
$string = preg_replace( '#^(<br\\b[^>]*/?>)+#i', '', $string );

Categories