Preg_replace string - php

I am creating a username from the users Billing First Name and Billing Last Name.
This in in. WooCommerce, though I suppose the cms is irrelevant to my question.
The following characters should be removed:
! # # $ % ^ & * ( ) ~ ` , . : ' " ; ; > < ? / \ |
Any number should be removed
The string must be in lowercase
All spaces must be replaced with hyphen.
Below is what I tried:
if(isset($_POST['billing_first_name']))
$fn = $_POST['billing_first_name'];
$fn = iconv('utf-8', 'us-ascii//TRANSLIT', $fn);
$fn = preg_replace('/[^a-z0-9-]+/', '-', strtolower($fn));
$fn = preg_replace("/-+/", '-', $fn);
$fn = trim($fn, '-');
if(isset($_POST['billing_last_name']))
$ln = $_POST['billing_last_name'];
$ln = iconv('utf-8', 'us-ascii//TRANSLIT', $ln);
$ln = preg_replace('/[^a-z0-9-]+/', '-', strtolower($ln));
$ln = preg_replace("/-+/", '-', $ln);
$ln = trim($ln, '-');
Example:
fn = Liz & Noël;
ln = John-Evan’s 2nd;
echo $fn . '-' . $ln;
Expected Outcome:
liznoel-johnevansnd
Computed Outcome:
liz-no-eljohn-evan-s-2nd

You can use
<?php
$fn = 'Liz & Noël';
$ln = 'John-Evan’s 2nd';
function process( $str )
{
$str = iconv('utf-8', 'us-ascii//TRANSLIT', $str);
$str = strtolower($str);
return preg_replace('~[^A-Za-z]+~u', '', $str);
}
echo process($fn) . '-' . process($ln);
Note that preg_replace('~[^A-Za-z]+~u', '', $str); removes any char other than an ASCII letter from any Unicode string. Since the hyphen appears between the two name parts, you cannot replace with a hyphen, you need to create the string from two parts using concatenation.

Related

How to trim filename extension, replace hyphens with spaces, and start each word with a capital?

I have a string like this:
$image = 'galaxy-s6.jpg';
I want to trim the .jpg, and replace the - with the space, and make the first letter of each word uppercase like this:
Galaxy S6
I tried
$name = str_replace('.jpg', '', $image);
$name = str_replace('-', ' ', $name);
array_map('ucfirst', explode(' ', $name));
I got
galaxy s6
Any hints for me?
You can use ucwords() function:
<?php
$image = 'galaxy-s6.jpg';
$name = str_replace('.jpg', '', $image);
$name = str_replace('-', ' ', $name);
echo ucwords($name);
?>
$name = str_replace('.jpg', '', $image); will replace .jpg with a blank.
$name = str_replace('-', ' ', $name); will replace - with a blank.
echo ucwords($name); will capitalise the first letter of each word (galaxy and s6)
Alternatively, you can also explode the last part of the filename, .jpg or any other file extension and remove it, using explode() function:
<?php
$image = 'galaxy-s6.jpg';
$name = explode(".", $image);
$name = str_replace('-', ' ', $name[0]);
echo ucwords($name);
?>
Thus, both methods will echo Galaxy S6.
array_map('ucfirst', explode(' ', $name));
The only issue here is that you're ignoring the return value of array_map. This would do it:
echo join(' ', array_map('ucfirst', explode(' ', $name)));
However, an overall saner approach is this:
echo ucwords(str_replace('-', ' ', pathinfo($image, PATHINFO_FILENAME)));
See:
http://php.net/pathinfo
http://php.net/ucwords
You can use this:
$string = "galaxy-s6.jpg";
$exploded = explode(".",$string);
$replace = str_replace("-", " ", $exploded[0]);
$upper = ucwords($replace);
echo $upper;
Result:
Galaxy S6
Explanation:
explode for exploding with (.)
replace - with space
get 0 index from exploded array
As #deceze suggest no need to ucfirst just use ucwords() for capital letter.
UPDATE 1:
For suppose if you have (.) between your file name than explode() will fail in this case you can handle this by using preg_replace();
// your string
$string = "galaxy-s6.jpg";
// replace after .
$removed = preg_replace('/\\.[^.\\s]{3,4}$/', '', $string);
// replace - between file name
$replace = str_replace("-", " ", $removed);
// ucwords for first letter capital
$upper = ucwords($replace);
echo $upper;
Just few functions :
<?php
$a = "galaxy-s6.jpg";
$a = str_replace(".jpg","",$a);
$a = str_replace("-"," ",$a);
echo ucwords($a)
?>
Demo : http://sandbox.onlinephpfunctions.com/code/213abb52e2aed4265c5bc1af45c544559ae9757f
Try out this code:
$string = 'galaxy-s6.jpg';
$name = str_replace('.jpg', '', $string);
$name = str_replace('-', ' ', $name);
$name = explode(' ', $name);
foreach ($name as $key => $value) {
$name[$key] = ucfirst($value);
}
$name = implode(' ', $name);
echo $name;// => Galaxy S6

Propper Regex Pattern

I need to check the incoming string and leave only characters, matching:
small case a-z letters
_ character
any numbers
only one dot (first one)
$string = 'contDADdas7.6.asdASDj_##e1!Ddd__aa#S.txt';
$pattern = "/[a-z_0-9]+/";
preg_match_all("/[a-z_0-9]+/", $name, $result);
echo implode('', $result[0]);
has to be
contdas7.6asdj_e1dd__aatxt
It matches first three points, how can I take only one first dot ?
You can try this:
$string = strrev($string);
$string = preg_replace('~[^a-z0-9_.]++|\.(?![^.]*$)~', '', $string);
$string = strrev($string);
An other way:
$strs = explode('.', $string);
if (count($strs)>1) {
$strs[0] .= '.' . $strs[1];
unset($strs[1]);
}
$string = preg_replace('~[^a-z0-9_.]++~', '', implode('', $strs));
<?php
$str = "contDADdas7.6.asdASDj_##e1!Ddd__aa#S.txt";
preg_match_all("/[a-z_0-9\.]+/", $str, $match);
$newstr = implode("", $match[0]);
echo substr_replace(str_replace(".", "", $newstr), ".", strpos($newstr, "."), 0);
Output:
contdas7.6asdj_e1dd__aatxt

Proper case title for City, State including apostrophe

I have this code:
$CapDeliveryCityANDState = str_replace('\, ', '\,', ucwords(str_replace('\,', '\, ', strtolower($CapDeliveryCityANDState))));
$CapDeliveryCityANDState = strrev(ucfirst(strrev($CapDeliveryCityANDState)));
that makes the first letter capital of every word and the rest lowercase and after the comma "," it makes the first two letters capital, but I want to add another thing and to make a letter capital if there is a "'" so, so far what I have works great for this example:
cHiCago, il would become Chicago, IL
but if it was o'fallon, mo it would be O'fallon, MO but I would like it to be O'Fallon, MO (capital after the apostrophe)
Thanks for the help...
SOLUTION IS:
$CapDeliveryCityANDState = str_replace('\, ', '\,', ucwords(str_replace('\,', '\, ', strtolower($CapDeliveryCityANDState))));
$CapDeliveryCityANDState = strrev(ucfirst(strrev($CapDeliveryCityANDState)));
if(strpos($CapDeliveryCityANDState, "'")) {
$pos = strpos($CapDeliveryCityANDState, "'") + 1;
}
$CapDeliveryCityANDState = substr_replace($CapDeliveryCityANDState, strtoupper($CapDeliveryCityANDState[$pos]), $pos, 1);
$CapDeliveryCityANDState[$l=strlen($CapDeliveryCityANDState)-2] = strtoupper($CapDeliveryCityANDState[$l]);
Added more to this code for anyone if they ever need it:
$CapDeliveryCityANDState = $contact_CityandStateSTR;
if(strlen($CapDeliveryCityANDState) >= 5){ //If more then 5 letters then do the below
$CapDeliveryCityANDState = str_replace('\, ', '\,', ucwords(str_replace('\,', '\, ', strtolower($CapDeliveryCityANDState))));
$CapDeliveryCityANDState = strrev(ucfirst(strrev($CapDeliveryCityANDState)));
if(strpos($CapDeliveryCityANDState, "'")) {
$pos = strpos($CapDeliveryCityANDState, "'") + 1;
$CapDeliveryCityANDState = substr_replace($CapDeliveryCityANDState, strtoupper($CapDeliveryCityANDState[$pos]), $pos, 1);
}
$mystringz = $CapDeliveryCityANDState;
$findmez = ',';
$posz = strpos($mystringz, $findmez);
if ($posz !== false) {
// IF NOT FALSE THEN CAP. LAST 2 LETTERS (STATE)
$CapDeliveryCityANDState[$l=strlen($CapDeliveryCityANDState)-2] = strtoupper($CapDeliveryCityANDState[$l]);
} else {
// ELSE IF FALSE THEN LEAVE AS IS
$CapDeliveryCityANDState = $contact_CityandStateSTR;
}
}
$CapDeliveryCityANDState = str_replace(" ,", ",", $CapDeliveryCityANDState); //remove space after city
$CapDeliveryCityANDState = str_replace(",", ", ", $CapDeliveryCityANDState); //add space after comma
$CapDeliveryCityANDState = preg_replace('!\s+!', ' ', $CapDeliveryCityANDState); //Check and remove double space
Find the apostrophe with strstr(). If it exists, explode the values into the two parts (before and after the apostrophe), capitalize them, then implode() them on the apostrophe again.

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;

How to remove all special characters from URL?

I have my class
public function convert( $title )
{
$nameout = strtolower( $title );
$nameout = str_replace(' ', '-', $nameout );
$nameout = str_replace('.', '', $nameout);
$nameout = str_replace('æ', 'ae', $nameout);
$nameout = str_replace('ø', 'oe', $nameout);
$nameout = str_replace('å', 'aa', $nameout);
$nameout = str_replace('(', '', $nameout);
$nameout = str_replace(')', '', $nameout);
$nameout = preg_replace("[^a-z0-9-]", "", $nameout);
return $nameout;
}
BUt I can't get it to work when I use special characters like ö and ü and other, can sombody help me here? I use PHP 5.3.
The first answer in this SO thread contains the code you need to do this.
And what about:
<?php
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?>
From: http://php.net/manual/en/function.urlencode.php
I wrote this function a while ago for a project I was working on and couldn't get RegEx to work. Its not the best way, but it works.
function safeURL($input){
$input = strtolower($input);
for($i = 0; $i < strlen($input); $i++){
$working = ord(substr($input,$i,1));
if(($working>=97)&&($working<=122)){
//a-z
$out = $out . chr($working);
} elseif(($working>=48)&&($working<=57)){
//0-9
$out = $out . chr($working);
} elseif($working==46){
//.
$out = $out . chr($working);
} elseif($working==45){
//-
$out = $out . chr($working);
}
}
return $out;
}
Here's a function to help with what you're doing, it's written in
Czech: http://php.vrana.cz/vytvoreni-pratelskeho-url.php
(and translated to English)
Here's another take on it (from the Symfony documentation):
<?php
function slugify($text)
{
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
// trim
$text = trim($text, '-');
// transliterate
if (function_exists('iconv'))
{
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
}
// lowercase
$text = strtolower($text);
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
if (empty($text))
{
return 'n-a';
}
return $text;
}

Categories