Replace multiple occurrences of same symbol using preg_replace? - php

Let's say I have a string like this:
$string = "hello---world";
How would I go about replacing the --- with a single hyphen?
The string could easily look like this instead:
$string = "hello--world----what-up";
The desired result should be:
$string = "hello-world-what-up";

$string = preg_replace('/-{2,}/','-',$string);

To remove them from the beginning and the end:
$string = trim($string, '-');

try $string = preg_replace('/-+/', '-', $string)

$string = preg_replace('/--+/', '-', $string);

Here's the function I'm using - works like a charm :)
public static function setString($phrase, $length = null) {
$result = strtolower($phrase);
$result = trim(preg_replace("/[^0-9a-zA-Z-]/", "-", $result));
$result = preg_replace("/--+/", "-", $result);
$result = !empty($length) ? substr($result, 0, $length) : $result;
// remove hyphen from the beginning (if exists)
$first_char = substr($result, 0, 1);
$result = $first_char == "-" ? substr($result, 1) : $result;
// remove hyphen from the end (if exists)
$last_char = substr($result, -1);
$result = $last_char == "-" ? substr($result, 0, -1) : $result;
return $result;
}

Related

preg_replace return an empty string without error

So there's my problem :
$var = "93 Avenue d'Aubière";
I used this $var with this function:
function stripAccents($str) {
$str = preg_replace('/[\x{00C0}\x{00C1}\x{00C2}\x{00C3}\x{00C4}\x{00C5}]/u','A', $str);
$str = preg_replace('/[\x{0105}\x{0104}\x{00E0}\x{00E1}\x{00E2}\x{00E3}\x{00E4}\x{00E5}]/u','a', $str);
$str = preg_replace('/[\x{00C7}\x{0106}\x{0108}\x{010A}\x{010C}]/u','C', $str);
$str = preg_replace('/[\x{00E7}\x{0107}\x{0109}\x{010B}\x{010D}}]/u','c', $str);
$str = preg_replace('/[\x{010E}\x{0110}]/u','D', $str);
$str = preg_replace('/[\x{010F}\x{0111}]/u','d', $str);
$str = preg_replace('/[\x{00C8}\x{00C9}\x{00CA}\x{00CB}\x{0112}\x{0114}\x{0116}\x{0118}\x{011A}]/u','E', $str);
$str = preg_replace('/[\x{00E8}\x{00E9}\x{00EA}\x{00EB}\x{0113}\x{0115}\x{0117}\x{0119}\x{011B}]/u','e', $str);
$str = preg_replace('/[\x{00CC}\x{00CD}\x{00CE}\x{00CF}\x{0128}\x{012A}\x{012C}\x{012E}\x{0130}]/u','I', $str);
$str = preg_replace('/[\x{00EC}\x{00ED}\x{00EE}\x{00EF}\x{0129}\x{012B}\x{012D}\x{012F}\x{0131}]/u','i', $str);
$str = preg_replace('/[\x{0142}\x{0141}\x{013E}\x{013A}]/u','l', $str);
$str = preg_replace('/[\x{00F1}\x{0148}]/u','n', $str);
$str = preg_replace('/[\x{00D2}\x{00D3}\x{00D4}\x{00D5}\x{00D6}\x{00D8}]/u','O', $str);
$str = preg_replace('/[\x{00F2}\x{00F3}\x{00F4}\x{00F5}\x{00F6}\x{00F8}]/u','o', $str);
$str = preg_replace('/[\x{0159}\x{0155}]/u','r', $str);
$str = preg_replace('/[\x{015B}\x{015A}\x{0161}]/u','s', $str);
$str = preg_replace('/[\x{00DF}]/u','ss', $str);
$str = preg_replace('/[\x{0165}]/u','t', $str);
$str = preg_replace('/[\x{00D9}\x{00DA}\x{00DB}\x{00DC}\x{016E}\x{0170}\x{0172}]/u','U', $str);
$str = preg_replace('/[\x{00F9}\x{00FA}\x{00FB}\x{00FC}\x{016F}\x{0171}\x{0173}]/u','u', $str);
$str = preg_replace('/[\x{00FD}\x{00FF}]/u','y', $str);
$str = preg_replace('/[\x{017C}\x{017A}\x{017B}\x{0179}\x{017E}]/u','z', $str);
$str = preg_replace('/[\x{00C6}]/u','AE', $str);
$str = preg_replace('/[\x{00E6}]/u','ae', $str);
$str = preg_replace('/[\x{0152}]/u','OE', $str);
$str = preg_replace('/[\x{0153}]/u','oe', $str);
$str = preg_replace('/[\x{0022}\x{0025}\x{0026}\x{0027}\x{00A1}\x{00A2}\x{00A3}\x{00A4}\x{00A5}\x{00A6}\x{00A7}\x{00A8}\x{00AA}\x{00AB}\x{00AC}\x{00AD}\x{00AE}\x{00AF}\x{00B0}\x{00B1}\x{00B2}\x{00B3}\x{00B4}\x{00B5}\x{00B6}\x{00B7}\x{00B8}\x{00BA}\x{00BB}\x{00BC}\x{00BD}\x{00BE}\x{00BF}]/u',' ', $str);
return $str;
}
This return an empty string if I use $var but it return the correct string if I use "93 Avenue d'Aubière" as a parameter.
I tried to use preg_last_error to check if there was any error but it return 0 that means no error.
I'm connectin my DB like this:
$db = new PDO('mysql:host=localhost;dbname=somedb;charset=utf8', 'username', 'password');
Getting data like this :
$sqlSelectCommandeExapaq = "SELECT * FROM commande_exapaq WHERE statut = 'en cours'";
$res = $db->query($sqlSelectCommande);
$arrayResCmd = $res->fetchAll();
Then I passed $arrayResCmd into this function :
public static function generateInterfaceFile($orders_array)
{
// Init file
$record = new DPDStation();
// Loop through each order
foreach ($orders_array as $order_data)
{
// Add data to file
$record->add($order_data['customer_adress'], 0, 35);
}
return $record;
}
And there is the DPDStation Constructor :
function __construct() {
$this->line = str_pad("", 1634);
$this->contenu_fichier = '';
}
And the add function :
function add($txt, $position, $length) {
$txt = $this->stripAccents($txt);
$this->line = substr_replace($this->line, str_pad($txt, $length), $position, $length);
}
And adding content into the file with :
$dpd = new DPDStation();
$record = $dpd->generateInterfaceFile($arrayResCmd);
file_put_contents($filename, '$VERSION=110'."\r\n", FILE_APPEND);
file_put_contents($filename, $record->contenu_fichier."\r\n", FILE_APPEND);
Because nothing was add to the file, I look into the stripAccents and the problem seems to come from it.
Thanks for your help :)

PHP + Modify string

I have got a string and would like to remove everything after a certain "dot"+word combination. For instance:
This.Is.A.Test
=> would become
This.Is.A
Were you looking to remove everything after a specific dot+word, or just remove the last dot+word? If you're looking for a specific word, try this:
$str = "This.Is.A.Test";
$find = ".A";
$index = strpos($str, $find);
if ($index !== false)
$str = substr($str, 0, $index + strlen($find));
echo $str; // "This.Is.A"
In response to #SuperSkunk:
If you wanted to match the whole word, you could do this:
$find = ".A.";
$str = "This.Is.A.Test";
$index = strpos($str, $find);
if ($index !== false)
$str = substr($str, 0, $index + strlen($find) - 1);
echo $str; // "This.Is.A"
$str = "This.Is.AB.Test";
$index = strpos($str, $find);
if ($index !== false)
$str = substr($str, 0, $index + strlen($find) - 1);
echo $str; // "This.Is.AB.Test" (did not match)
$str = "This.Is.A.Test"; $str = substr($str, 0, strrpos($str, "."));
$result = explode('.', $str, 4);
array_pop($result);
implode('.', $result);
I'll do something very simple like :
<?php
$string = 'This.Is.A.Test';
$parts = explode('.', $string);
array_pop($parts); // remove last part
$string = implode('.', $parts);
echo $string;
?>
$pos = strpos($haystack, ".A" );
$result = substr($haystack,0,$pos);
...something like this.

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;

Simple: How to replace "all between" with php? [duplicate]

This question already has answers here:
How to remove text between tags in php?
(6 answers)
Closed 3 years ago.
$string = "<tag>i dont know what is here</tag>"
$string = str_replace("???", "<tag></tag>", $string);
echo $string; // <tag></tag>
So what code am i looking for?
A generic function:
function replace_between($str, $needle_start, $needle_end, $replacement) {
$pos = strpos($str, $needle_start);
$start = $pos === false ? 0 : $pos + strlen($needle_start);
$pos = strpos($str, $needle_end, $start);
$end = $pos === false ? strlen($str) : $pos;
return substr_replace($str, $replacement, $start, $end - $start);
}
DEMO
$search = "/[^<tag>](.*)[^<\/tag>]/";
$replace = "your new inner text";
$string = "<tag>i dont know what is here</tag>";
echo preg_replace($search,$replace,$string);
outputs:
<tag>your new inner text</tag>
$string = "<tag>I do not know what is here</tag>";
$new_text = 'I know now';
echo preg_replace('#(<tag.*?>).*?(</tag>)#', '$1'.$new_text.'$2' , $string); //<tag>I know now</tag>
A generic and non-regex solution:
I've modified #felix-kling's answer. Now it only replaces text if it finds the needles.
Also, I've added parameters for replacing the needles, starting position and replacing all the matches.
I've used the mb_ functions for making the function multi-byte safe.
If you need a case insensitive solution then replace mb_strpos calls with mb_stripos.
function replaceBetween($string, $needleStart, $needleEnd, $replacement,
$replaceNeedles = false, $startPos = 0, $replaceAll = false) {
$posStart = mb_strpos($string, $needleStart, $startPos);
if ($posStart === false) {
return $string;
}
$start = $posStart + ($replaceNeedles ? 0 : mb_strlen($needleStart));
$posEnd = mb_strpos($string, $needleEnd, $start);
if ($posEnd === false) {
return $string;
}
$length = $posEnd - $start + ($replaceNeedles ? mb_strlen($needleEnd) : 0);
$result = substr_replace($string, $replacement, $start, $length);
if ($replaceAll) {
$nextStartPos = $start + mb_strlen($replacement) + mb_strlen($needleEnd);
if ($nextStartPos >= mb_strlen($string)) {
return $result;
}
return replaceBetween($result, $needleStart, $needleEnd, $replacement, $replaceNeedles, $nextStartPos, true);
}
return $result;
}
$string = "{ Some} how it {is} here{";
echo replaceBetween($string, '{', '}', '(hey)', true, 0, true); // (hey) how it (hey) here{
If "tag" changes:
$string = "<tag>i dont know what is here</tag>";
$string = preg_replace('|^<([a-z]*).*|', '<$1></$1>', $string)
echo $string; // <tag></tag>
If you don't know what's inside the <tag> tag, it's possible there is another <tag> tag in there e.g.
<tag>something<tag>something else</tag></tag>
And so a generic string replace function won't do the job.
A more robust solution is to treat the string as XML and manipulate it with DOMDocument. Admittedly this only works if the string is valid as XML, but I still think it's a better solution than a string replace.
$string = "<tag>i don't know what is here</tag>";
$replacement = "replacement";
$doc = new DOMDocument();
$doc->loadXML($str1);
$node = $doc->getElementsByTagName('tag')->item(0);
$newNode = $doc->createElement("tag", $replacement);
$node->parentNode->replaceChild($newNode, $node);
echo $str1 = $doc->saveHTML($node); //output: <tag>replacement</tag>
$string = "<tag>i dont know what is here</tag>"
$string = "<tag></tag>";
echo $string; // <tag></tag>
or just?
$string = str_replace($string, "<tag></tag>", $string);
Sorry, could not resist. Maybe you update your question with a few more details. ;)
If you need to replace the portion too then this function is helpful:
$var = "Nate";
$body = "Hey there {firstName} have you already completed your purchase?";
$newBody = replaceVariable($body,"{","}",$var);
echo $newBody;
function replaceVariable($body,$needleStart,$needleEnd,$replacement){
while(strpos($body,$needleStart){
$start = strpos($body,$needleStart);
$end = strpos($body,$needleEnd);
$body = substr_replace($body,$replacement,$start,$end-$start+1);
}
return $body;
}
I had to replace a variable put into a textarea that was submitted. So I replaced firstName with Nate (including the curly braces).

Replace any string before "/", PHP

I want to replace any string before "/", irrespective of the string length.
Thanks
Jean
one way, assuming you want to change the string before the first "/".
$str = "anystring/the_rest/blah";
$s = explode("/",$str);
$s[0]="new string";
print_r ( implode("/",$s) );
echo preg_replace('/^[^\/]+/', 'baz', 'foo/bar');
Something like that would be the most efficient, although i still prefer the preg_replace() technique
$pos = strpos($input, '/');
if ($pos >= 0) {
$output = $replacement . substr($input, $pos);
} else {
$output = $input;
}

Categories