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;
Related
I am working on scraping and then parsing an HTML string to get the two URL parameters inside the href. After scraping the element I need, $description, the full string ready for parsing is:
<a target="_blank" href="CoverSheet.aspx?ItemID=18833&MeetingID=773">Description</a><br>
Below I use the explode parameter to split the $description variable string based on the = delimiter. I then further explode based on the double quote delimiter.
Problem I need to solve: I want to only print the numbers for MeetingID parameter before the double quote, "773".
<?php
echo "Description is: " . htmlentities($description); // prints the string referenced above
$htarray = explode('=', $description); // explode the $description string which includes the link. ... then, find out where the MeetingID is located
echo $htarray[4] . "<br>"; // this will print the string which includes the meeting ID: "773">Description</a><br>"
$meetingID = $htarray[4];
echo "Meeting ID is " . substr($meetingID,0,3);
?>
The above echo statement using substr works to print the meeting ID, 773.
However, I want to make this bulletproof in the event MeetingID parameter exceeds 999, then we would need 4 characters. So that's why I want to delimit it by the double quotes, so it prints all numbers before the double quotes.
I try below to isolate all of the amount before the double quotes... but it isn't seeming to work correctly yet.
<?php
$htarray = explode('"', $meetingID); // split the $meetingID string based on the " delimiter
echo "Meeting ID0 is " . $meetingID[0] ; // this prints just the first number, 7
echo "Meeting ID1 is " . $meetingID[1] ; // this prints just the second number, 7
echo "Meeting ID2 is " . $meetingID[2] ; // this prints just the third number, 3
?>
Question, why is the array $meetingID[0] not printing the THREE numbers before the delimiter, ", but rather just printing a single number? If the explode function works properly, shouldn't it be splitting the string referenced above based on the double quotes, into just two elements? The string is
"773">Description</a><br>"
So I can't understand why when echoing after the explode with double quote delimiter, it's only printing one number at a time..
The reason you're getting the wrong response is because you're using the wrong variable.
$htarray = explode('"', $meetingID);
echo "Meeting ID0 is " . $meetingID[0] ; // this prints just the first number, 7
echo "Meeting ID1 is " . $meetingID[1] ; // this prints just the second number, 7
echo "Meeting ID2 is " . $meetingID[2] ; // this prints just the third number, 3
echo "Meeting ID is " . $htarray[0] ; // this prints 773
There's an easier way to do this though, using regular expressions:
$description = '<a target="_blank" href="CoverSheet.aspx?ItemID=18833&MeetingID=773">Description</a><br>';
$meetingID = "Not found";
if (preg_match('/MeetingID=([0-9]+)/', $description, $matches)) {
$meetingID = $matches[1];
}
echo "Meeting ID is " . $meetingID;
// this prints 773 or Not found if $description does not contain a (numeric) MeetingID value
There is a very easy way to do it:
Your Str:
$str ='<a target="_blank" href="CoverSheet.aspx?ItemID=18833&MeetingID=773">Description</a><br>';
Make substr:
$params = substr( $str, strpos( $str, 'ItemID'), strpos( $str, '">') - strpos( $str, 'ItemID') );
You will get substr like this :
ItemID=18833&MeetingID=773
Now do whatever you want to do!
I'm trying to echo a phpstring-message. This php string consists of html and php variables and comes form a database and i can't change that data.
$name = 'John';
$str = '<b>Hi {$name},</b><br/>How are you?';
echo $str;
So i'm trying to replace the php string, but it doesn't work. This is my code:
$str = str_replace('{', '\' . ', $str);
$str = str_replace('}', ' . \' ', $str);
I get: <b>Hi' . $name. ',</b><br/>How are you?
How do i get the string like this?
<b>Hi John,</b><br/>How are you?
Thank you in advance
Just do it like this, you won't be able to replace it with a concatenation:
echo str_replace('{$name}', $name, $str);
EDIT:
If you don't know the name of the variable just use this:
echo preg_replace('/\{(.*?)\}/', $name, $str);
it's already implemented in PHP, you can directly write the variable in double quote like this:
echo "<b>Hi $name,</b><br/>How are you?";
or for some more complex variables:
echo "<b>Hi {$user->name},</b><br/>How are you?";
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 .
I've got a problem with str_replace.
I have scraped a page with curl and now I want to replace an href id like this:
(all variables are present)
$search_result = str_replace("<href=\"?run=".$id."\">", "<href=\"?run=1111\">", $search_result);
The problem is that when I use the "<" and ">" characters in the str_replace it will not work.
Can anyone tell me why?
I also tried this (which does work like expected):
$test = "< something >";
$test = str_replace("<", "(", $test);
echo $test;
i'm not sure to have understand your question...
$test = "< something >";
$test = str_replace("<", "(", $test);
$test = str_replace(">", ")", $test);
echo $test;
this give me this output
( something )
so it works!
and doing a little mod to your code works fine on me, just try this:
$link = "hello world";
$search_result = str_replace('<a href="?run=1">', "<a href=\"?run=1111\">", $link);
echo $search_result;
Use this regular expression to replace the multiple occurance , as < and . are escape characters we have to escape them as shown below
value.replace(/>/g, '(');
Still having RegEx issues.. Need to match the following characters
a-zA-z9-0 , . ' " ( ) _ - : (SPACE)
Not all the values will have all these but could have them. I have everything withing but the parentheses, Single and Double Quoytes
/^[\w. ,\/:_-]+$/
UPDATE:
I got it working with this: "/^[\w. ,:()'\"-]+$/"
$val_1 = "Abh acb 123 . - _ 's ";
$val_2 = "Asc";
$val_3 = "234";
$val_4 = "nj%"; // Fail
$val_5 = "Help (me)";
$val_6 = "What's wrong?"; // Fail
$val_7 = "She's here";
$val_8 = "No: 123.00, 432.00";
$val_9 = 'Need to " Double" ';
$var_array = array($val_1, $val_2, $val_3, $val_4, $val_5, $val_6, $val_7, $val_8, $val_9);
foreach ($var_array as $k=>$d) {
if ((preg_match("/^[\w. ,:()'\"-]+$/", $d))) {
echo "Yeah it matches!!!<span style='color:green'>".$d."</span><br />";
} else {
echo "Try again, thie FAILED<span style='color:red'>".$d."</span><br />";
}
}
Thanks for all for helping out
$pat = "/^[\w. ,\\/:_()'\"-]/";
To match all those, you just need:
preg_match("/[a-zA-Z0-9,.'\"()_- :]/", $string);
/^[-a-zA-Z0-9,.'"()_: ]+$/
This should work. But if you put it into a string be sure to escape the needed quotes.
With the help of the other submitting I have found the solution that works:
"/^[\w. ,:()'\"-]+$/"
Thanks to all for the help