how can I replace [link](#) to link? - php

I want to do something like stackoverflow. actually changing this style []() to this style . here is my try:
$str = '[link](#)';
$str = str_replace('[','<a href="',$str); // output: <a href="link](#)
$str = str_replace(']','">',$str); // output: <a href="link">(#)
$str = str_replace('(','',$str); // output: <a href="link">#)
$str = str_replace(')','</a>',$str); // output: #
but now, I need to change link with #, how can I do that ?

You want to take a look at preg_replace(), with this you can use a regex to replace it, e.g.
$str = preg_replace("/\[(.*?)\]\((.*?)\)/", "<a href='$2'>$1</a>", $str);
regex explanation:
\[(.*?)\]\((.*?)\)
\[ matches the character [ literally
1st Capturing group (.*?)
.*? matches any character (except newline)
Quantifier: *? Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
\] matches the character ] literally
\( matches the character ( literally
2nd Capturing group (.*?)
.*? matches any character (except newline)
Quantifier: *? Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
\) matches the character ) literally

Related

Extract time within parentheses using PHP

This is my first time using the trim function and I want to get the Time excluding the open and close parenthesis of my string. Can you give me hints and suggestions on how to do this?
$string = "Updated by Carewina Almonte (04/02/2018 21:58:32)";
echo trim($string, "Updated by Carewina Almonte (04/02/2018");
exit();
In php, You can do get this and this works if and only if date and time always appears at the end of string -
$string = "Updated by Carewina Almonte (04/02/2018 21:58:32)";
$time = substr($string,-9,8);
echo $time;
$string = "Updated by Carewina Almonte (04/02/2018 21:58:32)";
if(preg_match("/\d{2}:\d{2}:\d{2}/", $string , $match))
{
echo $match[0];
}
Regular expression should be used in this case.
You can use preg_match for this task:
$str = 'Updated by Carewina Almonte (04/02/2018 21:58:32)';
preg_match('/(?<=\(\d{2}\/\d{2}\/\d{4} ).*(?=\))/', $str, $match);
echo $match[0];
Breakdown:
Positive Lookbehind (?<=\(). Assert that the Regex below matches:
\( matches the character ( literally (case sensitive)
.* matches any character (except for line terminators)
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\d{2} matches a digit (equal to [0-9])
{2} Quantifier — Matches exactly 2 times
\/ matches the character / literally (case sensitive)
Positive Lookahead (?=\)). Assert that the Regex below matches:
\) matches the character ) literally (case sensitive)
For you example string you might match what is between parenthesis using \(\K[^)]+(?=\)).
This will match an opening parenthesis \( and then use \K to reset the starting point of the reported match.
After that match NOT a closing parenthesis one or more times [^)]+ and a positive lookahead to assert that what follows is a closing parenthesis (?=\)).
Then you could create a DateTime using or use DateTime::createFromFormat using $matches[0] and extract the time:
$re = '/\(\K[^)]+(?=\))/';
$str = 'Updated by Carewina Almonte (04/02/2018 21:58:32)';
preg_match($re, $str, $matches);
$dateTime = new DateTime($matches[0]);
if ($dateTime !== false) {
echo $dateTime->format('H:i:s');
}
Test

split string in numbers and text but accept text with a single digit inside

Let's say I want to split this string in two variables:
$string = "levis 501";
I will use
preg_match('/\d+/', $string, $num);
preg_match('/\D+/', $string, $text);
but then let's say I want to split this one in two
$string = "levis 5° 501";
as $text = "levis 5°"; and $num = "501";
So my guess is I should add a rule to the preg_match('/\d+/', $string, $num); that looks for numbers only at the END of the string and I want it to be between 2 and 3 digits.
But also the $text match now has one number inside...
How would you do it?
To slit a string in two parts, use any of the following:
preg_match('~^(.*?)\s*(\d+)\D*$~s', $s, $matches);
This regex matches:
^ - the start of the string
(.*?) - Group 1 capturing any one or more characters, as few as possible (as *? is a "lazy" quantifier) up to...
\s* - zero or more whitespace symbols
(\d+) - Group 2 capturing 1 or more digits
\D* - zero or more characters other than digit (it is the opposite shorthand character class to \d)
$ - end of string.
The ~s modifier is a DOTALL one forcing the . to match any character, even a newline, that it does not match without this modifier.
Or
preg_split('~\s*(?=\s*\d+\D*$)~', $s);
This \s*(?=\s*\d+\D*$) pattern:
\s* - zero or more whitespaces, but only if followed by...
(?=\s*\d+\D*$) - zero or more whitespaces followed with 1+ digits followed with 0+ characters other than digits followed with end of string.
The (?=...) construct is a positive lookahead that does not consume characters and just checks if the pattern inside matches and if yes, returns "true", and if not, no match occurs.
See IDEONE demo:
$s = "levis 5° 501";
preg_match('~^(.*?)\s*(\d+)\D*$~s', $s, $matches);
print_r($matches[1] . ": ". $matches[2]. PHP_EOL);
print_r(preg_split('~\s*(?=\s*\d+\D*$)~', $s, 2));

Remove occurrence of string in php

i'm beginning in PHP and i try to remove all occurrence of a string. My string is something like that.
'This is [a test] try [it]'
What i'm trying to do is remove all occurrence of the [] with the text inside the square bracket.
I want the results to be something like:
'This is try'
.
How can i achieve that?
You could use preg_replace function.
preg_replace('~\[[^\]]*\]~', '', $string);
[^\]]* negated character class which matches any character but not of a closing bracket ], zero or more times.
Add an extra trim function to remove the leading or trailing spaces from the resultant string.
$string = 'This is [a test] try [it]';
$result = preg_replace('~\[[^\]]*\]~', '', $string);
echo trim($result, " ");
You can try this:
$myString = 'This is [a test] try [it]';
$myString = preg_replace('/\[[\w ]+\] */', '', $myString);
var_dump($myString);
Explanations:
/\[[\w ]+\]/g
\[ matches the character [ literally
[\w ]+ match a single character present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
\w match any word character [a-zA-Z0-9_]
' ' the literal character ' '
\] matches the character ] literally

change line to bold, if it ends with a colon, and only contains one word

How do I change the word to bold, if there is only one word on a line with a colon at the end?
data comes from at text field in mysql database, and code is php
You can capture the word and substitute surrounded by <b>
^(\w+):$
Live demo
Sample code:
$re = "/^(\\w+):$/m";
$str = "abc:\nabc\nabc:xyz\n";
$subst = '<b>$1</b>';
$result = preg_replace($re, $subst, $str);
Pattern explanation:
^ the beginning of the string
( group and capture to \1:
\w+ word characters (a-z, A-Z, 0-9, _) (1 or more times)
) end of \1
: ':'
$ before an optional \n, and the end of the string
Use this:
$replaced = preg_replace('~^\w+:$~', '<b>$0</b>', $yourstring);
Explanation
The ^ anchor asserts that we are at the beginning of the string
The \w+ matches one or more word chars
: matches the colon
The $ anchor asserts that we are at the end of the string
We replace with <b>, the overall match (referenced by $0) and </b>

php - preg_replace / backreference - Syntax to extract parts from mail address

I do have a var like this:
$mail_from = "Firstname Lastname <email#domain.com>";
I would like to receive either an
array(name=>"firstname lastname", email=>"email#domain.com")
or
the values in two separate vars ($name = "...", $email = "...")
I have been playing around with preg_replace but somehow do not get it done ...
Did extensive search but did not find a way to get this done.
This is the closest I got:
$str = 'My First Name <email#domain.com>';
preg_match('~(?:"([^"]*)")?\s*(.*)~',$str,$var);
print_r($var);
echo "<br>Name: ".$var[0];
echo "<br>Mail: ".$var[2];
How do I get "email#domain.com" into $var['x]?
Thank you.
This works for your example and should always work, when the email is within angle brackets.
$str = 'My First Name <email#domain.com>';
preg_match('~(?:([^<]*?)\s*)?<(.*)>~', $str, $var);
print_r($var);
echo "<br>Name: ".$var[1];
echo "<br>Mail: ".$var[2];
Explanation:
(?:([^<]*?)\s*)? matches optionally everything that is not a < and everything except the trailing whitespace is stored in group 1.
<(.*)> matches something between angle brackets and store it in group 2.
//trythis
$mail_from = "Firstname Lastname <email#domain.com>";
$a = explode("<", $mail_from);
$b=str_replace(">","",$a[1]);
$c=$a[0];
echo $b;
echo $c;
Try this:
(?<=")([^"<>]+?) *<([^<>"]+)>(?=")
Explanation:
<!--
(?<=")([^"<>]+?) *<([^<>"]+)>(?=")
Options: ^ and $ match at line breaks
Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=")»
Match the character “"” literally «"»
Match the regular expression below and capture its match into backreference number 1 «([^"<>]+?)»
Match a single character NOT present in the list “"<>” «[^"<>]+?»
Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
Match the character “ ” literally « *»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match the character “<” literally «<»
Match the regular expression below and capture its match into backreference number 2 «([^<>"]+)»
Match a single character NOT present in the list “<>"” «[^<>"]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “>” literally «>»
Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=")»
Match the character “"” literally «"»
-->
Code:
$result = preg_replace('/(?<=")([^"<>]+?) *<([^<>"]+)>(?=")/m', '<br>Name:$1<br>Mail:$2', $subject);

Categories