I have a product database and I am displaying trying to display them as clean URLs, below is example product names:
PAUL MITCHELL FOAMING POMADE (150ml)
American Crew Classic Gents Pomade 85g
Tigi Catwalk Texturizing Pomade 50ml
What I need to do is display like below in the URL structure:
www.example.com/products/paul-mitchell-foaming-gel(150ml)
The problem I have is I want to do the following:
1. Remove anything inside parentheses (and the parentheses)
2. Remove any numbers next to g or ml e.g. 400ml, 10g etc...
I have been banging my head trying different string replaces but cant get it right, I would really appreciate some help.
Cheers
function makeFriendly($string)
{
$string = strtolower(trim($string));
$string = str_replace("'", '', $string);
$string = preg_replace('#[^a-z\-]+#', '_', $string);
$string = preg_replace('#_{2,}#', '_', $string);
$string = preg_replace('#_-_#', '-', $string);
return preg_replace('#(^_+|_+$)#D', '', $string);
}
this function helps you for cleaning url. (also cleans numbers)
try this,
<?php
$url = 'http%3A%2F%2Fdemo.com';
$decodedurl= urldecode($url);
echo $decodedurl;
?
$from = array('/\(|\)/','/\d+ml|\d+g/','/\s+/');
$to = array('','','-');
$sample = 'PAUL MITCHELL FOAMING POMADE (150ml)';
$sample = strtolower(trim(preg_replace($from,$to,$sample),'-'));
echo $sample; // prints paul-mitchell-foaming-pomade
Try this:
trim(preg_replace('/\s\s+/', ' ', preg_replace("/(?:\(.*?\)|\d+\s*(?:g|ml))/", "", $input)));
// "abc (def) 50g 500 ml 3m(ghi)" --> "abc 3m"
Related
I have a string which contains n\ by mistake (as imported from csv). So,I just want to replace n\ with \n.
Possible conditions : n\,\n\n, n\\n,n\n\
$string = "hello\n how n\n\ are you?\n\nis everything\nn\ok buddy, n\ where have you been. \n";
Try this. It will remove all the possible matches as per your question:-
$str = "main_string_goes_here";
$replace = "n\,\n\n,n\n\,\nn\,n\\n";
$arr = explode(",",$replace);
foreach($arr as $value)
{
str_replace($value,"\n",$str);
}
Happy Coding :-)
Use this:
str_replace("n\","\n",$string);
Here we search for the string, find the value "n\" and then replace the value with "\n". Update this example with your conditions.
Try like this
$string = 'hello\n how n\n\ are you?\n\nis everything\nn\ok buddy, n\ where have you been. \n';
$string = str_replace('n\\n\\','&new*',$string);
$string = str_replace('\\n\\n','&old*',$string);
$string = str_replace('n\\','\\n',$string);
$string = str_replace('&new*','\\n\\n',$string);
echo $string = str_replace('&old*','\\n\\n',$string);
Live demo : https://eval.in/904353
As other says to replace "n\" to "\n" will not work. You need to escape \ backslash also
Use this:
<?php
echo $string = 'hello\n how n\n\ are you?\n\nis everything\nn\ok buddy, n\ where have you been. \n';
$new_str = preg_replace('~[\\\\/:*?"<>|]~', ' ', $string);
echo $text = str_replace('n', '', $new_str);
?>
You can try this.
$string = 'hello\n how n\n\ are you?\n\nis everything\nn\ok buddy, n\ where have you been. \n';
echo str_replace('n\\', '\n',$string );
I have a string for example : I am a boy
I want to show this on my url for example in this way : index.php?string=I-am-a-boy
My program :
$title = "I am a boy";
$number_wrds = str_word_count($title);
if($number_wrds > 1){
$url = str_replace(' ','-',$title);
}else{
$url = $title;
}
What if I have a string : Destination - Silicon Valley
If I implement the same logic my url will be : index.php?string=Destination---Silicon-Valley
But I want to show only 1 hyphen.
I want to show a hyphen instead of a plus sign..
url_encode() will eventually insert plus symbols.. So it's not helping here.
Now if I use minus symbol then if the actual string is Destination - Silicon Valley, then the url will look like
Destination-Silicon-Valley and not
Destination---Silicon-Valley
Check this stackoverflow question title and the url. You will know what I am saying.
Check this
Use urlencode() to send strings along with an url:
$url = 'http://your.server.com/?string=' . urlencode($string);
In comments you told, that you don't want urlencode, you'll just replace spaces by - characters.
First, you should "just do it", the if conditional and str_word_count() is just overhead. Basically your example should look like this:
$title = "I am a boy";
$url = str_replace(' ','-', $title);
That's it.
Further you told that this would make problems if the original string already contains a -. I would use preg_replace() instead of str_replace() to solve that problem. Like this:
$string = 'Destination - Silicon Valley';
// replace spaces by hyphen and
// group multiple hyphens into a single one
$string = preg_replace('/[ -]+/', '-', $string);
echo $string; // Destination-Silicon-Valley
Use preg_replace instead:
$url = preg_replace('/\s+/', '-', $title);
\s+ means "any whitespace character (\t\r\n\f (space, tab, line feed, newline)).
use urlencode:
<?php
$s = "i am a boy";
echo urlencode($s);
$s = "Destination - Silicon Valley";
echo urlencode($s);
?>
return:
i+am+a+boy
Destination+-+Silicon+Valley
and urldecode:
<?php
$s = "i+am+a+boy";
echo urldecode($s)."\n";
$s = "Destination+-+Silicon Valley";
echo urldecode($s);
?>
return:
i am a boy
Destination - Silicon Valley
just use urlencode() and urldecode(). It’s for sending Data with GET in the URL.
The title may sound odd, but im kind of trying to set up this preg_replace that takes care of messy writers for a textarea. It has to:
if there is an exclamation sign, there should not be another one in a row.
if there is a ., the comma wins and it has to be ,
when there is one+ spaces before a coma, it should be reduced to nothing.
the sentence cannot start or end with a comma.
there should never be more than 2 of the same letters joined together.
a space must be always present after a comma.
E.g.:
,My house, which is green., is nice!
My house..., which is green, is nice!!!
My house ,which is green,,, is nice!!
The end result should always be:
My house, which is green, is nice!
Is there an already built regex that takes care of this?
Solution check out FakeRainBrigand's solution below!
I might have to use this for my own sites... nice idea!
<?php
$text = 'My hooouse..., which is greeeeeen , is nice!!! ,And pretty too...';
$pats = array(
'/([.!?]\s{2}),/', # Abc. ,Def
'/\.+(,)/', # ......,
'/(!)!+/', # abc!!!!!!!!
'/\s+(,)/', # abc , def
'/([a-zA-Z])\1\1/', # greeeeeeen
'/,(?!\s)/');
$fixed = preg_replace($pats, '$1', $text);
echo $fixed;
echo "\n\n";
?>
And the 'modified' version of $text: "My house, which is green, is nice! And pretty too."
UPDATE: Here's the version that handles "abc,def" -> "abc, def".
<?php
$text = 'My hooouse..., which is greeeeeen ,is nice!!! ,And pretty too...';
$pats = array(
'/([.!?]\s{2}),/', # Abc. ,Def
'/\.+(,)/', # ......,
'/(!)!+/', # abc!!!!!!!!
'/\s+(,)/', # abc , def
'/([a-zA-Z])\1\1/'); # greeeeeeen
$fixed = preg_replace($pats, '$1', $text);
$really_fixed = preg_replace('/,(?!\s)/', ', ', $fixed);
echo $really_fixed;
echo "\n\n";
?>
I would think this is a bit slower since it's an additional function call.
- $result = preg_replace('/!+/', '!', $subject);
- $result = preg_replace('/\.*,/', ',', $subject);
- $result = preg_replace('/\s+(?=,)/', '', $subject);
- $result = preg_replace('/^,*|,*$/', '', $subject);
- $result = preg_replace('/([a-z])\1+/i', '$1$1', $subject);
- $result = preg_replace('/,(?!\s)/', ', ', $subject);
One by one matching to your rules :)
I remember doing this before, but can't find the code. I use str_replace to replace one character like this: str_replace(':', ' ', $string); but I want to replace all the following characters \/:*?"<>|, without doing a str_replace for each.
Like this:
str_replace(array(':', '\\', '/', '*'), ' ', $string);
Or, in modern PHP (anything from 5.4 onwards), the slighty less wordy:
str_replace([':', '\\', '/', '*'], ' ', $string);
str_replace() can take an array, so you could do:
$new_str = str_replace(str_split('\\/:*?"<>|'), ' ', $string);
Alternatively you could use preg_replace():
$new_str = preg_replace('~[\\\\/:*?"<>|]~', ' ', $string);
For example, if you want to replace search1 with replace1 and search2 with replace2 then following code will work:
print str_replace(
array("search1","search2"),
array("replace1", "replace2"),
"search1 search2"
);
// Output: replace1 replace2
str_replace(
array("search","items"),
array("replace", "items"),
$string
);
If you're only replacing single characters, you should use strtr()
You could use preg_replace(). The following example can be run using command line php:
<?php
$s1 = "the string \\/:*?\"<>|";
$s2 = preg_replace("^[\\\\/:\*\?\"<>\|]^", " ", $s1) ;
echo "\n\$s2: \"" . $s2 . "\"\n";
?>
Output:
$s2: "the string "
I had a situation whereby I had to replace the HTML tags with two different replacement results.
$trades = "<li>Sprinkler and Fire Protection Installer</li>
<li>Steamfitter </li>
<li>Terrazzo, Tile and Marble Setter</li>";
$s1 = str_replace('<li>', '"', $trades);
$s2 = str_replace('</li>', '",', $s1);
echo $s2;
result
"Sprinkler and Fire Protection Installer", "Steamfitter ", "Terrazzo, Tile and Marble Setter",
I guess you are looking after this:
// example
private const TEMPLATE = __DIR__.'/Resources/{type}_{language}.json';
...
public function templateFor(string $type, string $language): string
{
return \str_replace(['{type}', '{language}'], [$type, $language], self::TEMPLATE);
}
In my use case, I parameterized some fields in an HTML document, and once I load these fields I match and replace them using the str_replace method.
<?php echo str_replace(array("{{client_name}}", "{{client_testing}}"), array('client_company_name', 'test'), 'html_document'); ?>
I need to find the first occurance of a colon ':' and take the complete string before that and append it to a link.
e.g.
username: #twitter nice site! RT www.google.com : visited!
needs to be converted to:
username: nice site! RT www.google.com : visited!
I've already got the following regex that converts the string #twitter to a clickable URL:
E.g.
$description = preg_replace("/#(\w+)/", "#\\1", $description);
Any ideas : )
I'd use string manipulation for this, rather than regex, using strstr, substr and strlen:
$username = strstr($description, ':', true);
$description = '' . $username . ''
. substr($description, strlen($username));
$regEx = "/^([^:\s]*)(.*?:)/";
$replacement = "\1\2";
I have not tested the code, but it should work as is. Basically you need to capture after #twitter too.
$description = preg_replace("%([^:]+): #twitter (.+)%i",
"#\\1: \\2",
$description);
The following should work -
$description = preg_replace("/^(.+?):\s#twitter\s(.+?)$/", "#\\1: \\2", $description);
Direct answer to your question:
$string = preg_replace('/^(.*?):/', '$1:', $string);
But I assume that you are parsing twitter RSS or something similar. So you can just use /^(\w+)/.