PHP trim problem - php

I asked earlier how can I get rid of extra hyphens and whitespace added at the end and beginning of user submitted text for example, -ruby-on-rails- should be ruby-on-rails you guys suggested trim() which worked fine by itself but when I added it to my code it did not work at all it actually did some funky things to my code.
I tried placing the trim() code every where in my code but nothing worked can someone help me to get rid of extra hyphens and whitespace added at the end and beginning of user submitted text?
Here is my PHP code.
$tags = preg_split('/,/', strip_tags($_POST['tag']), -1, PREG_SPLIT_NO_EMPTY);
$tags = str_replace(' ', '-', $tags);

Update the trim statement to the following in order to update each item in the array:
foreach($tags as $key=>$value) {
$tags[$key] = trim($value, '-');
}
That should allow you to trim each value based on a string being expected.

If you have a string you can do this to strip hyphens from the beginning and end:
$tag = trim($tag, '-');
Your problem is that preg_split returns an array, but trim takes a string. You need to do the above for every string in the array.
Regarding trimming whitespace: if you are first converting all whitespace to hyphens then it should not be necessary to trim whitespace afterwards - the whitespace will already be gone. But be careful because the terms "whitespace" and "space" have different meanings. Your question seems to muddle these two terms.

Verify that the hyphen character you're attempting to trim is the same hyphen character that is wrapping -ruby-on-rails-. For example, these are all different characters that look similar: -, –, —, ―.

Im new to StackOverflow.com so I hope the function I wrote helps you in some way. You can specify what characters you want it to trim in the second parameter, for your example I've set it to just remove whitespace and 'dashes' by default, i've tested it using 'ruby-on-rails' and a somewhat extreme example of '- -- - - ruby-on-rails - -- - - -' and both produce the result: 'ruby-on-rails'.
The regular expression might be a bit of a q&d way of going about it but I hope it helps you, just reply if you have any problems implementing it or w/e.
function customTrim($s,$c='- ')
{
preg_match('#'.($a='[^'.$c.']').'.{1,}'.$a.'#',$s,$match);
return $match[0];
}

Related

preg_replace and possible json issues

I need to replace a whitespace at the beginning of any newline. I am using JSON to send over the POST values and suspect this may have something to do with it not working.
$str='
This is a string.
This should be left justified by removing whitespaces preceding it.
';
preg_replace('/^\s+/', '', $str);
Running this, works as expected. When I attempt to use it with my POST array, the whitespaces remain. Why?
Does JSON play a part in this?
EDIT:
Just to clarify, the array being sent over is not JSON encoded, it is a PHP array using JSON POST.
I just tried modifying my regex a bit and can at least verify that preg_replace is doing something. If I do: /\s+/, all spaces are removed. So, I know it's working somewhat.
Is my regex correct?
EDIT #2
This is making me crazy. I figured I would just trim the whitespace in my javascript and call it a day, but I'm getting the same exact result.
Is there any other circumstance that would stop this regex from matching?
/^\s+/
What about this:
$str='
This is a string.
This should be left justified by removing whitespaces preceding it.
';
preg_replace('/^\s+/m', '', $str);
I've just added the m modifier. See http://us3.php.net/manual/en/reference.pcre.pattern.modifiers.php
try this:
foreach($trim_val as $key => $value) {
$trim_val[$key] = trim($value);
}
$json = json_encode($trim_val);
already solution is here given by someone, check

Regex for PHP seems simple but is killing me

I'm trying to make a replace in a string with a regex, and I really hope the community can help me.
I have this string :
031,02a,009,a,aaa,AZ,AZE,02B,975,135
And my goal is to remove the opposite of this regex
[09][0-9]{2}|[09][0-9][A-Za-z]
i.e.
a,aaa,AZ,AZE,135
(to see it in action : http://regexr.com?3795f )
My final goal is to preg_replace the first string to only get
031,02a,009,02B,975
(to see it in action : http://regexr.com?3795f )
I'm open to all solution, but I admit that I really like to make this work with a preg_replace if it's possible (It became something like a personnal challenge)
Thanks for all help !
As #Taemyr pointed out in comments, my previous solution (using a lookbehind assertion) was incorrect, as it would consume 3 characters at a time even while substrings weren't always 3 characters.
Let's use a lookahead assertion instead to get around this:
'/(^|,)(?![09][0-9]{2}|[09][0-9][A-Za-z])[^,]*/'
The above matches the beginning of the string or a comma, then checks that what follows does not match one of the two forms you've specified to keep, and given that this condition passes, matches as many non-comma characters as possible.
However, this is identical to #anubhava's solution, meaning it has the same weakness, in that it can leave a leading comma in some cases. See this Ideone demo.
ltriming the comma is the clean way to go there, but then again, if you were looking for the "clean way to go," you wouldn't be trying to use a single preg_replace to begin with, right? Your question is whether it's possible to do this without using any other PHP functions.
The anwer is yes. We can take
'/(^|,)foo/'
and distribute the alternation,
'/^foo|,foo/'
so that we can tack on the extra comma we wish to capture only in the first case, i.e.
'/^foo,|,foo/'
That's going to be one hairy expression when we substitute foo with our actual regex, isn't it. Thankfully, PHP supports recursive patterns, so that we can rewrite the above as
'/^(foo),|,(?1)/'
And there you have it. Substituting foo for what it is, we get
'/^((?![09][0-9]{2}|[09][0-9][A-Za-z])[^,]*),|,(?1)/'
which indeed works, as shown in this second Ideone demo.
Let's take some time here to simplify your expression, though. [0-9] is equivalent to \d, and you can use case-insensitive matching by adding /i, like so:
'/^((?![09]\d{2}|[09]\d[a-z])[^,]*),|,(?1)/i'
You might even compact the inner alternation:
'/^((?![09]\d(\d|[a-z]))[^,]*),|,(?1)/i'
Try it in more steps:
$newList = array();
foreach (explode(',', $list) as $element) {
if (!preg_match('/[09][0-9]{2}|[09][0-9][A-Za-z]/', $element) {
$newList[] = $element;
}
}
$list = implode(',', $newList);
You still have your regex, see! Personnal challenge completed.
Try matching what you want to keep and then joining it with commas:
preg_match_all('/[09][0-9]{2}|[09][0-9][A-Za-z]/', $input, $matches);
$result = implode(',', $matches);
The problem you'll be facing with preg_replace is the extra-commas you'll have to strip, cause you don't just want to remove aaa, you actually want to remove aaa, or ,aaa. Now what when you have things to remove both at the beginning and at the end of the string? You can't just say "I'll just strip the comma before", because that might lead to an extra comma at the beginning of the string, and vice-versa. So basically, unless you want to mess with lookaheads and/or lookbehinds, you'd better do this in two steps.
This should work for you:
$s = '031,02a,009,a,aaa,AZ,AZE,02B,975,135';
echo ltrim(preg_replace('/(^|,)(?![09][0-9]{2}|[09][0-9][A-Za-z])[^,]+/', '', $s), ',');
OUTPUT:
031,02a,009,02B,975
Try this:
preg_replace('/(^|,)[1-8a-z][^,]*/i', '', $string);
this will remove all substrings starting with the start of the string or a comma, followed by a non allowed first character, up to but excluding the following comma.
As per #GeoffreyBachelet suggestion, to remove residual commas, you should do:
trim(preg_replace('/(^|,)[1-8a-z][^,]*/i', '', $string), ',');

preg_replace to convert a user input string to a link pattern

I want to convert user input string
"something ... un// important ,,, like-this"
to
"something-un-important-like-this"
So basically remove all recurring special characters with "-". I've googled and came to this
preg_replace('/[-]+/', '-', preg_replace('/[^a-zA-Z0-9_-]/s', '-', strtolower($string)));
I'm curious as to know if this can be done with a single preg_replace().
Just to clear things out:
replace all special characters and blank space with a hyphen(-). If more occurrence appear consecutively replace them with single hyphen
My solution works perfectly as I want to but I'm looking to do the same in a single call
There was a similar question yesterday, but I don't have it at hand.
In your current first pattern:
[^a-zA-Z0-9_-]
you're looking for a single character only. If you make that a greedy match for one or more, the regular expression engine will automatically replace multiple of these with a single one:
[^a-zA-Z0-9_-]+
^- + = one or more
You then still have the problem that existing - inside the string are not caught, so you need to take them out of the "not-in" character class:
[^a-zA-Z0-9_]+
This then should do it:
preg_replace('/[^a-zA-Z0-9_]+/s', '-', strtolower($string));
And as it's only lowercase, you do not need to look for A-Z as well, just another reduction:
preg_replace('/[^a-z0-9_]+/s', '-', strtolower($string));
See as well Repetition and/or Quantifiers of which the + is one of (see Repetition­Docs; Repetition with Star and Plus­regular-expressions.info).
Also if you take a look at the modifiers­Docs, you'll see that the s (PCRE_DOTALL) modifier is not necessary:
$urlSlug = preg_replace('/[^a-z0-9_]+/', '-', strtolower($string));
Hope this helps and explains you a little about the regular expression you're using and also where you can find further documentation which is always helpful.
Try This:
preg_replace('/[^a-zA-Z0-9_-]+/s', '-', strtolower($string));

Is there a better way to strip/form this string in PHP?

I am currently using what appears to be a horribly complex and unnecessary solution to form a required string.
The string could have any punctuation and will include slashes.
As an example, this string:
Test Ripple, it\'s a comic book one!
Using my current method:
str_replace(" ", "-", trim(preg_replace('/[^a-z0-9]+/i', ' ', str_replace("'", "", stripslashes($string)))))
Returns the correct result:
Test-Ripple-its-a-comic-book-one
Here is a breakdown of what my current (poor) solution is doing in order to achieve the desired output:-
Strip all slashes from the string
remove any apostrophes with str_replace
remove any remaining punctuation using preg_replace and replace it with whitespace
Trim off any extra whitespace from the beginning/end of string which may have been caused by punctuation.
Replace all whitespace with '-'
But there must be a better and more efficient way. Can anyone help?
Personally it looks fine to me however I would make one small change.
Change
preg_replace("/[^a-z0-9]+/i"
to the following
preg_replace("/[^a-zA-Z0-9\s]/"

can anybody explain ther 4 lines of php code I am so confused

code-
$res=$this->post("http://address.mail.yahoo.com/?_src=&VPC=print",$post_elements);
$emailA=array();
$bulk=array();
$res=str_replace(array(' ',' ',PHP_EOL,"\n","\r\n"),array('','','','',''),$res);
preg_match_all("#\<tr class\=\"phead\"\>\<td colspan\=\"2\"\>(.+)\<\/tr\>(.+)\<div class\=\"first\"\>\<\/div\>\<div\>\<\/div\>(.+)\<\/div\>#U",$res,$bulk);
$post_element is an array, I am mainly consern ablut str_replace and preg_replace_all function line
$res = str_replace(
array(' ',' ',PHP_EOL,"\n","\r\n"),
array('','','','',''),
$res);
means: replace the strings in the first array with the values in the second array, e.g. turn two spaces into nothing, turn three spaces into nothing, turn the platform dependent newline character to nothing, turn newline character to nothing, turn carriagereturn followed by newline to nothing.
preg_match_all("#\<tr class\=\"phead\"\>\<td colspan\=\"2\"\>(.+)\<\/tr\>(.+)\<div class\=\"first\"\>\<\/div\>\<div\>\<\/div\>(.+)\<\/div\>#U",$res,$bulk);
means the developer had no clue that HTML should not be parsed with Regex.
in that code str_replace removes whitespace characters and preg_match_all matches by regex some values in the html, there is no preg_replace_all in the code
$res=$this->post("http://address.mail.yahoo.com/?_src=&VPC=print",$post_elements);
$emailA=array();
-> post data to http://address.mail.yahoo.com/?_src=&VPC=print and get the response, assign to $res
$res=str_replace(array(' ',' ',PHP_EOL,"\n","\r\n"),array('','','','',''),$res);
--> delete any while-space, tab-space, end-line ...
and reference here for the last one
http://php.net/manual/en/function.preg-match-all.php

Categories