PHP Replace all characters other than [a-zA-Z0-9\-] [duplicate] - php

This question already has answers here:
How do I write a regex in PHP to remove special characters?
(3 answers)
Closed 9 years ago.
I would like to replace all characters in a string other than [a-zA-Z0-9\-] with a space.
I've found this post and no matter how many times I tweak the REGEX, I can't get it to "don't match [a-zA-Z0-9-], only match and replace other characters".
At the moment, I have the following:
$original_name = trim(' How to get file creation & modification date/times in Python? ');
$replace_strange_characters = preg_replace("/^((?!([a-zA-Z0-9\-]+)*))$/", " ", $original_name);
// Returns: How to get file creation & modification date/times in Python?
echo $replace_strange_characters;
I wish for it to replace all of the strange characters with a space ' ', thus returning:
How to get file creation modification date times in Python?
I'm really struggling with these "don't match" scenarios.
Here's my code so far: http://tehplayground.com/#2NFzGbG7B

You may try this (You mentioned you want to keep dash)
$original_name = trim(' How to get file creation & modification date/times in Python? ');
$replace_strange_characters = preg_replace('/[^\da-z-]/i', ' ', $original_name);
echo $replace_strange_characters;
DEMO.

Wouldn't this regex do it?
[^a-zA-Z0-9\-]
Oh, and why are you doing this btw?

Try this
$replace_strange_characters = preg_replace("([^a-zA-Z0-9\-\?])", " ", $original_name);
The previous answer strip out the ?

Related

PHP - Can't Remove Carriage Return / Space [duplicate]

This question already has answers here:
What is HTML Entity '
'?
(2 answers)
Closed 5 years ago.
I am reading from a MySQL Database.
The field upc reads as:
811657019822
843018021328
I only want the first numbers; there is a space/carriage return and for some reason I cannot explode it out or trim it out. When I convert to XML it displays as:
<g:gtin>811657019822
843018021328</g:gtin>
Here is what I have tried in PHP and the result:
When I do a var_dump it shows this:
string(25) "811657019822
843018021328"
Notice how they are not all on one line?
It doesn't appear to be a line break as the XML returns a Carriage Return. Any ideas on what to try to remove everything after the first numbers?
UPDATE
As pointed out by #Don't Panic I have erroneously mistaken my slashes the wrong way and should of only been using \r.
This is what worked correctly:
explode("\r", $product['upc']);
Explode with '/r/n' won't work for a couple of reasons. For one you'd need to use a double quoted string, with backslashes instead of forward slashes, like "\r\n". But there isn't a \n, just an \r.
Try using
explode("\r", $yourString);

How to remove white space in PHP generate css class? [duplicate]

This question already has answers here:
How do I strip all spaces out of a string in PHP? [duplicate]
(4 answers)
Closed 6 years ago.
I would like to remove white space in a php generated css code, I have different title header which would like to generate through php code.
Titles are like 1) Baby Day Care 2) Baby Night Care
My php codes are like:
<div class="wistia<?php echo $subject->title;?>">
So when I got the class, I got like wistiaBaby Day Care or wistiaBaby Night Care
But I want the class will be look like wistiaBabyDayCare or wistiaBabyNightCare
(I want space removed between text).
So how I am going to achieve that?
That should to the trick:
<div class="wistia<?php echo str_replace(' ', '', $subject->title);?>">
This just uses the str_replace function where you replace the first character with the 2nd character for a given string.
To remove any whitespace simply use preg_replace (regex):
<div class="wistia<?php echo preg_replace('/\s+/', '', $subject->title);?>">

PHP - Unable to remove whitespace from string [duplicate]

This question already has answers here:
Trim whitespace ASCII character "194" from string
(7 answers)
Closed 6 months ago.
I have a piece of code that reads in values from a CSV file, all working grand and then each individual record is validated and used in an API call to an external source, all of this is working grand.
Now today I have a CSV file uploaded that when I open it it looks to have 3 spaces at the end of each entry in the CSV which causes the API call to fail.
I've tried using trim() but it doesn't do anything, I've also tried using preg_replace('/^((?=^)(\s*))|((\s*)(?>$))/si', '', $pValue) and this isn't having any affect either.
I opened the CSV file in Notepad++ and enabled it to show all symbols, there are clearly 3 spaces and the CR and LF.
Has anyone come across an issue like this before, code snippets below and an example on codepad.
EDIT:
Example: http://codepad.org/DfjzPcUU
Code snippets, if more is needed please let me know.
$vCSVData = self::getCSVData($vPendingFilePath);
foreach ($vCSVData AS $vKey => $vValue)
{
echo self::getNubmer($vValue);
...
}
getCSVData():
private function getCSVData($pFilePath)
{
return call_user_func_array('array_merge', array_map('str_getcsv', file($pFilePath, FILE_SKIP_EMPTY_LINES)));
}
CSV File Snippet:
Blue Table   
Green Chair  
Temp. Table   
As it turns out that what I thought was white space was actually ASCII 194 characters (Thanks to MikeB) for figuring this out, as trim, rtrim, preg_replace, str_replace with the normal " " (empty space) check didn't work the below snippet is what worked for me.
preg_replace("/[\xA0\xC2]/", "", "Table ")
xA0 is char 160 and xC2 is char 194.
Also you can use trim in this instance by using the below statement, using trim over preg_replace is slightly faster for processing time, with that said the overheads in each case and the difference are negligible, in my case either will suffice.
trim("Table ", "\xA0\xC2")
Example: http://codepad.org/8H5Ut2KA
I was able to find out what the 'space' was by using the below code snippet:
var_dump(ord($vString{5}));

Remove euro sign from string [duplicate]

This question already has answers here:
Unformat money when parsing in PHP
(8 answers)
Closed 9 years ago.
I have a php string which contains a currency. In this case it is a € but to make it future proof I would also like to replace other currency's. How can I filter this currency symbol out?
I tried preg replace but don't know the key to filter currency notations out, also I saw a couple of posts in which they did it entirely different, but couldn't manage to get them to work.
Tried your suggestions guys, still doesn't work. If I add a "," to the suggestions below in this post it does remove the , from the price so it does seem to do something. But the € sign remains.
The price is coming from a woocommerce array, and right before I want to remove the € sign I use a "strip_tags" command. Maybe that has to do something with it. If is use a if else statement to see if it is a string it echo's true, so it isn't a float or anything.
If you want to do it quick and easy, just do a string replacement:
$symbols = array('$', '€', '£');
$unformatted = str_replace($symbols, '', $price_string);
Why not write a simple str_replace() ?
<?php
function strip_currency($str)
{
return str_replace(array('$','€','£','pуб'),'',$str); // You can add-up currency symbols here
}
$yourstr='I have 10$ with me !';
echo $yourstr = strip_currency($yourstr); //"prints" I have 10 with me !
Demo

Strip RTF strings with PHP - Regex [duplicate]

This question already has answers here:
Regular Expression for extracting text from an RTF string
(11 answers)
Closed 9 years ago.
A column in the database I work with contains RTF strings, I would like to strip these out using PHP, leaving just the sentence between.
It is a MS SQL database 2005 if I recall correctly.
An example of the kind of strings pulled from the database (need any more let me know, all the rest are similar):
{\rtf1\ansi\ansicpg1252\deff0\deflang2057{\fonttbl{\f0\fnil\fcharset0 Tahoma;}}
\viewkind4\uc1\pard\lang1033\f0\fs17 ASSEMBLE COMPONENTS AS DETAILED ON DRAWING.\lang2057\fs17\par
}
I would like this to be stripped to only return:
ASSEMBLE COMPONENTS AS DETAILED ON DRAWING.
Now, I have successfully managed to strip the characters in ASP.NET for a previous project, however I would like to do so using PHP. Here is the regular expression I used in ASP.NET, which works flawlessly may I add:
"(\{.*\})|}|(\\\S+)"
However when I try to use the same expression in PHP with a preg_replace it does not strip half of the characters.
Any regex gurus out there?
Use this code. it will work fine.
$string = preg_replace("/(\{.*\})|}|(\\\S+)/", "", $string);
Note that I added a '/' in the beginning and at the end '/' in the regex.

Categories