PHP - Convert a string with dashes while removing first word - php

$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;

Related

PHP trim and keep only first and last part

I have variables as follow in PHP
steve_s_baue
marine_camp_se_bell
mike_wane
I want to only keep the first and last part:
steve_baue
marine_bell
mike_wane
I tried to use trim but got stuck.
EDIT: Here is what I tried to far
$row = $pre_results[$i];
$name = $row -> name;
$text = preg_replace('~[^\pL\d]+~u', '_', $name);
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
$text = preg_replace('~[^-\w]+~', '', $text);
$text = trim($text, '_');
$text = preg_replace('~-+~', '_', $text);
$text = strtolower($text);
Any suggestions?
function firstlast($var,$seperator) {
$varr = explode($seperator, $var);
$first = current($varr);
$last = end($varr);
return $first.'_'.$last;
}
$seperator='_';
$old = 'marine_camp_se_bell';
$new = firstlast($old, $seperator);
echo $new;
If you put original strings in an array, you can run array_walk(); with this function
You can check this:
http://nimb.ws/dVHzZJ and
http://nimb.ws/ENgTCm
<?php
$a = "steve_s_baue";
$temp=explode("_",$a);
$arr=array($temp[0],$temp[2]);
print_r(implode("_",$arr));
?>
Do it with explode function, I made a basic example working
<?php
$name = "marine_camp_se_bell";
$var = explode("_",$name);
print_r (explode("_",$name));
//than print as array
echo "</br>";
echo $var[0];
echo "</br>";
echo $var[3];
?>
$name = "john_dont_do_some_doe";
$array = explode("_", $name);
$last = count($array) - 1;
echo $array[0]."_". $array[$last]; //shows: john_doe
*not tested, but should do the job

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 all paragraphs based on order (after the 2rd, 3th or 4th...)

I got this
$description = '<p>text1</p><p>text2</p><p>text3</p><p>text4</p><p>textn</p>'
I want to remove only what comes after <p>text3</p>
My result would be:
$description = '<p>text1</p><p>text2</p><p>text3</p>'
My guess is that we need to use preg_replace with some regex but I can't manage to write a working one.
You could...
function str_occurance($needle, $haystack, $occurance) {
$occurance += 2;
$arr = explode($needle, $haystack, $occurance);
unset($arr[0]);
$arr = array_values($arr);
$key = count($arr) - 1;
unset($arr[$key]);
$str = $needle . implode($needle, $arr);
return $str;
}
Not the prettiest, but it works.
Edit: To use:
$description = '<p>text1</p><p>text2</p><p>text3</p><p>text4</p><p>textn</p>';
$split = '<p>';
$return = 3;
$new = str_occurance($needle, $description, $return);
echo $new; // returns <p>text1</p><p>text2</p><p>text3</p>

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 );

Remove Last String if its ', '

i have string like this
$string = 'aaaaaa, bbbbbb, cccccc, ';
and i want to modified it to be like this
$string = 'aaaaaa, bbbbbb, cccccc';
the last ',' and space is removed.
how to do this in php?
what is the function needed the achieve that?
my full code is like this
if(isset($_POST['accomodation'])) $accomodation = 'Accomodation, ';
if(isset($_POST['dance'])) $dance = 'Dance Lessons, ';
if(isset($_POST['vacation'])) $vacation = 'Vacation planning, ';
if(isset($_POST['group'])) $group = 'Group Vacation, ';
if(isset($_POST['inprivate'])) $inprivate = 'Private Vacation, ';
if(isset($_POST['land'])) $land = 'Land purchase/lease';
if(isset($_POST['all'])) $all = 'All';
#$interest = $accomodation.$dance.$vacation.$group.$inprivate.$land;
#echo $string;
*sorry for such dumb question, it's been so long i didn't touch native PHP programming
rtrim() function:
rtrim($string,', ');
but how are you defining the string? It may be that you can build it without the comma and space.
EDIT
$interests = array();
if(isset($_POST['accomodation'])) $interests[] = 'Accomodation';
if(isset($_POST['dance'])) $interests[] = 'Dance Lessons';
if(isset($_POST['vacation'])) $interests[] = 'Vacation planning';
if(isset($_POST['group'])) $interests[] = 'Group Vacation';
if(isset($_POST['inprivate'])) $interests[] = 'Private Vacation';
if(isset($_POST['land'])) $interests[] = 'Land purchase/lease';
if(isset($_POST['all'])) $all = 'All';
$interest = implode(', ',$interests);
echo $interest;
$string = preg_replace('/\s*,\s*$/', '', $string);
or, way cooler:
$string = rtrim($string, " ,");
Note that it does not matter the order of the characters in the pattern string.
#You last update.
This changes some things. You could put all your variables in one array and then implode it. Like so:
$items = array();
$items[] = $accomodation = 'Accomodation';
$items[] = $dance = 'Accomodation';
...
$result = implode(', ', $items)
$string = preg_replace( "/,\s*$/","",$string);
Should do the trick
Is it always a comma then a space at the end?
substr($string, 0, -2)
Often times, you can avoid the trailing comma altogether by changing the way you build the string. For example:
$count = 0;
foreach ($this as $that) {
if ($count != 0) {
$string .= ',';
}
$string .= $that['stuff'];
$count++;
}
Would remove the possibility of any trailing comma at the end, no matter the combination of results.

Categories