PHP trim and keep only first and last part - php

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

Related

How to echo explode array?

EDIT: More clear: I want to echo $data as an array.
I have this:
$lic = $_GET['lic'];
$locationtodb = '../../files/';
$licenses = $locationtodb.'filea.txt';
$SearchLicense = $lic;
$pattern = preg_quote($SearchLicense, '/');
$pattern = "/^.*$pattern.*\$/m";
preg_match_all($pattern, $licenses, $matches);
$wholeLine = implode("\n", $matches[0]);
$data = explode(":", $wholeLine);
I can use somethings like this to replace strings:
$CurrentLine = $lic.':'.'active'.':'.$data[2];
$NewLine = $lic.':'.'suspended'.':'.$data[2];
$new_contents = file_get_contents($licenses);
$new_contents = str_replace($CurrentLine,$NewLine,$new_contents);
file_put_contents($licenses,$new_contents);
And it does work !
But if I typed something like:
echo $data[2];
It give nothing ...
Why?
Thanks.
Solution discovered!
$licenses = $locationtodb.'filea.txt';
Must be:
$licenses = file_get_contents($locationtodb.'filea.txt');

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.

echo end of url without backslash

http://www.mywebsite/product-tag/animal/
How to I echo animal without the backslash and in big caps like this:
ANIMAL
$link = 'http://www.mywebsite/product-tag/animal/';
$parts = explode( '/', $link );
echo(strtoupper($parts[4]));
If you want auto searching, then you need to use preg_match.
<?php
$string = 'http://www.mywebsite/product-tag/animal/';
$urlparts = explode("/", $string);
$animal = ($string[strlen($string)-1] == '/'? $urlparts[count($urlparts)-2] : end($urlparts));
echo strtoupper($animal);
?>
actually I just figured it out
$r = $_SERVER['REQUEST_URI'];
$r = explode('/', $r);
$r = array_filter($r);
$r = array_merge($r, array());
$endofurl = $r[1];
echo $endofurl;

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;

Replace empty spaces with ### from Text between " " in a string in PHP

I have a string like this one text more text "empty space".
How can I replace the space in "empty space" and only this space with ###?
$string = 'text more text "empty space"';
$search = 'empty space';
str_replace($search, 'empty###space', $string);
How about this, with no regular expressions:
$text = 'foo bar "baz quux"';
$parts = explode('"', $text);
$inQuote = false;
foreach ($parts as &$part) {
if ($inQuote) { $part = str_replace(' ', '###', $part); }
$inQuote = !$inQuote;
}
$parsed = implode('"', $parts);
echo $parsed;
$somevar = "empty space";
$pattern = "/\s/";
$replacement = "###";
$somevar2 = preg_replace($pattern, $replacement, $somevar);
echo $somevar2;
$string = "My String is great";
$replace = " ";
$replace_with = "###";
$new_string = str_replace($replace, $replace_with, $string);
This should do it for you. http://www.php.net/manual/en/function.str-replace.php
Edited after you comments
Maybe it's not the best solution, but you can do it like this:
$string = 'text more text "empty space"';
preg_match('/(.*)(".*?")$/', $string, $matches);
$finaltext = $matches[1] . str_replace(' ', '###', $matches[2]);

Categories