Spaces Changed to Whitespace - php

The code below produces an unexpected result:
$row = 'one //There are spaces here
two ';
$row = explode(PHP_EOL,$row);
$row = $row[0];
preg_match('/( +)$/',$row,$matches);
When using var_dump($matches);, the output is:
array(0) {
}
But, it should be something like this:
array(2) {
[0]=>string(8) " "
[1]=>string(8) " "
}
Replacing PHP_EOL with "\n" makes no difference.
Using preg_match('/(\s+)$/',$row,$matches); produces the expected result:
array(2) {
[0]=>string(8) " "
[1]=>string(8) " "
}
The expected also happens when using:
$row = 'one ';
preg_match('/( +)$/',$row,$matches);
But, obviously, these both have their own reasons to not be used.
My question is: Why does PHP not recognize the spaces as spaces but only as whitespace?
Example: http://sandbox.onlinephpfunctions.com/code/a6f3ea8b422671d86a37b765986395b1dd6f94e8

You need to use "\n\r" instead of PHP_EOL or space
$row = explode("\n\r",$row);
$row = $row[0];
preg_match('/( +)$/',$row,$matches);
Now as you see you can use space in pattern for regExp

Related

How to remove whitespaces from the beginning and end of loop phrase

i need to remove whitespaces from the beginning and end of loop phrase
All words come from an loop, and look like this: " Hello all people "
I'm using the code -
$appliedFilters = Mage::getSingleton('catalog/layer')->getState()->getFilters();
foreach ($appliedFilters as $item) {
if ($item->getFilter()->getRequestVar() == 'b_car' || 'c_model' || 'd_year') {
$n_str = string.replace("\"", "", $item->getLabel()));
echo $n_str;
}
}
This code returns "Helloallpeople"
But i need "Hello all people"
Please help!
UPDATED
var_dump($item->getLabel()); returns string(7) "Hello " string(8) "all " string(5) "People "
Try Regx like the following:
$returnValue = preg_replace("/>\s+(.*)\s+</", '>$1<', '<a> Hello all people <a/>');
I am keeping the old answer for reference.
But if you simply want to remove leading and trailing spaces; use trim()
Update:
If you want to trim each and every element of an array; you can map trim function to it.
Then you can also implode the array to a string.
<?php
$str = array(" Hello all ", " Hello all people ", " all people ", " Hello people ");
$n_str = array_map("trim",$str);
var_dump($n_str);
echo implode(" ",$n_str);
?>
Update 2:
Ok I got it; It's not an array. It's a loop.
Every time $item->getLabel() returns just a string. it's not an array.
Following should help you.
$appliedFilters = Mage::getSingleton('catalog/layer')->getState()->getFilters();
$result = "";
foreach ($appliedFilters as $item) {
if ($item->getFilter()->getRequestVar() == 'b_car' || 'c_model' || 'd_year') {
$result .= " ".trim($item->getLabel());
}
}
echo trim($result);
Try this:
$words = $item->getLabel(); //array(" Hello", "all ", "people ");
echo trim(preg_replace("/\s+/", " ", implode($words, " ")));
// Output: Hello all people
See demo

PHP sprintf space padding

I have the following line in my code which displays my output in 6 characters with leading zeros.
$formatted_value = sprintf("%06d", $phpPartHrsMls);
I want to replace the leading zeros with spaces. Have tried all the examples found by searching this site and others and cannot figure it out.
Here are some I have tried:
$formatted_value = sprintf("%6s", $phpPartHrsMls);
$formatted_value = printf("[%6s]\n", $phpPartHrsMls); // right-justification with spaces
In the browser, spaces will always be collapsed.
Try:
<pre><?php echo $formatted_value; ?></pre>
And once you're satisfied with that, take a look at the CSS white-space:pre-wrap - a very useful property!
This will align the left with spaces:
$formatted_value = sprintf("%6s", $phpPartHrsMls);
echo "<pre>" . $formatted_value . "</pre>";
This will align the right with spaces:
$formatted_value = sprintf("%-6s", $phpPartHrsMls);
echo "<pre>" . $formatted_value . "</pre>";
If you want to print only six digits, and others to remove:
$formatted_value = sprintf("%-6.6s", $phpPartHrsMls);
echo "<pre>" . $formatted_value . "</pre>";
One more thing, the browser will generally ignore the spaces, so it's better to wrap your output in <pre> tag.
Changing leading zeroes to leading spaces:
$formatted_value = sprintf("%' 6s", $phpPartHrsMls);
Try str_pad.
str_pad($phpPartHrsMls, 6, " ", STR_PAD_LEFT);
you use %06d please try some larger number .
your code can some thing like below try :
printf('%20.2f', $phpPartHrsMls);
and you can use for space on your html .

Weird issue with concatenate variables

I am a weird issue regarding my class property here
I have the following:
$this->tableData = '<table>';
$this->tableData .= $string;
echo $this->tableData => output <table>
I want to concatenate more string to my $this->tableData but it seems like nothing is added.
I know $string is not null and contains characters
Did I do something wrong here?
Thanks!
To see if your string is not null you should use var_dump() or print_r() functions.
Example:
$this->tableData = '<table>';
echo "Dumping tableData: " . var_dump($this->tableData);
$this->tableData .= $string;
echo "Dumping tableData 2: " . var_dump($this->tableData);
echo "Dumping string: " . var_dump($string);
That way you will see exactly what is going on.
Is your variable $string containing a HTML tag, something like <p></p> or else ?
This could be "hidden" if you print_r it inside a browser.

Merging preg_match_all and preg_replace

I have some code running which finds out hashtags in the string and turns them into links. I have done this using preg_match_all as shown below:
if(preg_match_all('/(#[A-z_]\w+)/', $postLong, $arrHashTags) > 0){
foreach ($arrHashTags[1] as $strHashTag) {
$long = str_replace($strHashTag, ''.$strHashTag.'', $postLong);
}
}
Also, for my search script, I need to bold the searched keywords in the result string. Something similar to the below code using preg_replace:
$string = "This is description for Search Demo";
$searchingFor = "/" . $searchQuery . "/i";
$replacePattern = "<b>$0<\/b>";
preg_replace($searchingFor, $replacePattern, $string);
The problem that I am having is that both have to work together and should be thrown as a combined result. One way I can think of is to run the resultant string from preg_match_all with the preg_replace code but what if the tags and the searched string are the same? The second block will bold my tag as well which is not desired.
update the code i'm running based on the answer given below but it still doesn't work
if(preg_match_all('/(#[A-z_]\w+)/', $postLong, $arrHashTags) > 0){
foreach ($arrHashTags[1] as $strHashTag) {
$postLong = str_replace($strHashTag, ''.$strHashTag.'', $postLong);
}
}
And immediately after this, i run this
$searchingFor = "/\b.?(?<!#)" . $keystring . "\b/i";
$replacePattern = "<b>$0<\/b>";
preg_replace($searchingFor, $replacePattern, $postLong);
Just so you know, this is all going inside a while loop, which is generating the list
You just need to modify you the search pattern to avoid ones that start with a '#'
$postLong = "This is description for Search Demo";
if(preg_match_all('/(#[A-z_]\w+)/', $postLong, $arrHashTags) > 0){
foreach ($arrHashTags[1] as $strHashTag) {
$postLong = str_replace($strHashTag, ''.$strHashTag.'', $postLong);
}
}
# This expression finds any text with 0 or 1 characters in front of it
# and then does a negative look-behind to make sure that the character isn't a #
searchingFor = "/\b.?(?<!#)" . $searchQuery . "\b/i";
$replacePattern = "<b>$0<\/b>";
preg_replace($searchingFor, $replacePattern, $postLong);
Or if you don't need an array of the available hashes for another reason, you could use preg_replace only.
$postLong = "This is description for #Search Demo";
$patterns = array('/(#[A-z_]\w+)/', "/\b.?(?<!#)" . $searchQuery . "\b/i");
$replacements = array(''.$0.'', ' "<b>$0<\/b>');
preg_replace($patterns, $replacements, $postLong);

Replace every space in the beginning of the string

Using php preg_replace.
Tried:
$test = " 123";
$test = preg_replace("/^\s/","?",$test);
echo '|' . $test;
Outputs:
|? 123
What I need:
|???????123
Also tried another variants, but they all replace only FIRST space or ALL-IN-ONE...
Spaces inside of the string or at the end of the string - should NOT be touched.
You can probably do this much easier without regular expressions, utilizing strspn:
$whitespaceCount = strspn($test, " \t\r\n");
$test = str_repeat("?", $whitespaceCount).substr($test, $whitespaceCount);
<?php
$test = " 12 3 s";
$test = preg_replace_callback("/^([\s]*)([^\s]*)/","mycalback",$test);
echo '|' . $test;
function mycalback($matches){
return str_replace (" ", "?", $matches[1]).$matches[2];
}
?>
output:
|??????12 3 s
why you just dont try this:
echo '|' . preg_replace('/\s/','?',' 123');
Try this : remove ^ from pattern which checks for the beginning of the string, So what happens is it only replaces the space at the beginning (just one space)
$test = " 123";
$test = preg_replace("/\s/","?",$test);
echo '|' . $test;
$test = " 123";
$test = preg_replace("/^[ ]|[ ]/","?",$test);
echo '|' . $test;

Categories