Change ocurrence inside a string - php

I am needing to change occurrence of string or numbers in php. In this situation, I need to change this, if it happens:
[code:154545edppy]
// my code here
[/code]
to this
[code]
// my code here
[/code]
I need to verify if letters and strings appear inside de opening block code. I am trying to do this with str_replace, but it's not working.
my code now:
$text = "[code:54as] [/code]";
$text = str_replace("[code: {(\d)}{(\w)}]", "[code]", $text);
$text = str_replace("[/code: {(\d)}{(\w)}]", "[/code]", $text);
echo $text;

str_replace is static. Use preg_replace with a regex and you can accomplish your task.
Something like:
$text = "[code:54as] [/code]";
echo preg_replace('~(\[/?.*?):.*?\]~', '$1]', $text);
Should do it.
PHP Demo: https://eval.in/643544
Regex demo: https://regex101.com/r/mD1bM3/1
If you only want to replace numbers and letters after the : use a character class in place of the second .*?. [A-Za-z\d]*?.

Related

Remove text after link

So I have an #mentions function on my site that users input themselves but can do something line:
#foo Hello This is some mention text included.
I would like to remove just the text (Everything after #foo) The content comes through the streamitem_content:
$json['streamitem_content_usertagged'] =
preg_replace('/(^|\s)#(\w+)/', '\1#$1',
$json['streamitem_content']);
Give this a try
$json['streamitem_content'] = '#foo Hello This is some mention text included.';
$json['streamitem_content_usertagged'] =
preg_replace('/#(\w+)/', '#$1',
$json['streamitem_content']);
echo $json['streamitem_content_usertagged'];
Output:
#foo Hello This is some mention text included.
Preg_replace will only replace what it finds so you don't need to find content you aren't interested. If you did want to capture multiple parts of a string though capture groups increase by one after each group (). So this
preg_replace('/(^|\s)#(\w+)/', '$1#$2',
$json['streamitem_content']);
echo $json['streamitem_content_usertagged'];
would actually be
preg_replace('/(^|\s)#(\w+)/', '$1#$2',
$json['streamitem_content']);
Update:
$json['streamitem_content'] = '#foo Hello This is some mention text included.';
$json['streamitem_content_usertagged'] =
preg_replace('/#(\w+).*$/', '#$1',
$json['streamitem_content']);
echo $json['streamitem_content_usertagged'];
Output:
#foo
If the content you want to replace after #foo can extended to multiple lines use the s modifier.
Regex101 Demo: https://regex101.com/r/tX1rO0/1
So pretty much the regex says find an # then capture all continuous a-zA-Z0-9_ characters. After a those continuos characters we don't care go to the end of the string.
You can use this:
preg_replace('/^\s*#(\w+)/', '#$1',
$json['streamitem_content']);
This removes the leading white space, and includes the # in the hyperlink's text (not the link argument).
If you need to keep the leading white space in tact:
preg_replace('/^(\s*)#(\w+)/', '$1#$2',
$json['streamitem_content']);
You could use explode(); and str_replace(); . They might have a speed advantage over preg.
Assuming the line is available as a variable (e.g. $mention):
$mention = $json['streamitem_content'];
$mention_parts = explode(" ", $mention);
$the_part_you_want = str_replace('#','', $mention_parts[0]);
// or you could use $the_part_you_want = ltrim($mention_parts[0], '#');
$json['streamitem_content_usertagged'] = '#' . $mention_parts[0] . '';
or use trim($mention_parts[0]); to remove any whitespace if it is unwanted.
You could use fewer variables and reuse $mention as array but this seemed a clearer way to illustrate the principle.

How to replace string with tags used

I want to replace the string "<Reason/>" with empty space or just nothing.
I tried str_replace('<Reason/>','',$string) but it won't take the tags.
I tried str_preg('<Reason/>','', $string) but it leaves the the tags "<>".
I tried str_preg('/^<Reason/>/','', $string) but its gives me exception with unknown modifier '>'.
What can I do to remove the whole string along with tags "<Reason/>"?
You probably forgot to assign the result back to the original variable.
The following code works:
$string = str_replace('<Reason/>','',$string);
Full example:
$string = '<Reason/>lalala<Reason/>';
$string = str_replace('<Reason/>','',$string);
echo $string;
Output
lalala
for Case Insensitive, use
str_ireplace()
instead of `
str_replace()
`

preg_replace() pattern to remove brackets and content in php

I want to remove the brackets with its content using preg_replace(), but i am unable to use a lazy(non-greedy) in the pattern since the end bracket is the end character, the text in between the brackets is always a random character length and can contain numbers, underscores, and hyphens.
code-
$array = array(
"Text i want to keep (txt to remove)",
"Random txt (some more random txt)",
"Keep this (remove)",
"I like bananas (txt)"
);
$pattern = "#pattern#";
foreach($array as $new_txt){
$new_outputs .= preg_replace($pattern, '', $new_txt)."\n";
}
echo $new_outputs;
Wanted output-
Text i want to keep
Random txt
Keep this
I like bananas
I do not use regular expressions much and couldn't find anything to solve my problem.
The following regular expression should do it:
$pattern = '#\(.*?\)#';
.*? is a non-greedy match of anything.
$new_outputs .= preg_replace('#\([^\)]*\)$#','',$new_txt);
This might help you:
$pattern = "/\([^)]*\)+/";
foreach($array as $new_txt){
$new_outputs .= preg_replace($pattern, '', $new_txt)."\n";
}

Php replace exact word

Here is my problem:
Using preg_replace('#\b(word)\b#','****',$text);
Where in text I have word\word and word, the preg_replace above replaces both word\word and word so my resulting string is ***\word and ***.
I want my string to look like : word\word and ***.
Is this possible? What am I doing wrong???
LATER EDIT
I have an array with urls, I foreach that array and preg_replace the text where url is found, but it's not working.
For instance, I have http://www.link.com and http://www.link.com/something
If I have http://www.link.com it also replaces http://www.link.com/something.
You are effectively specifying that you don't want certain characters to count as word boundary. Therefore you need to specify the "boundaries" yourself, something like this:
preg_replace('#(^|[^\w\\])(word)([^\w\\]|$)#','**',$text);
What this does is searches for the word surrounded by line boundaries or non-word characters except the back slash \. Therefore it will match .word, but not .word\ and not `\word. If you need to exclude other characters from matching, just add them inside the brackets.
You could just use str_replace("word\word", "word\word and"), I dont really see why you would need to use a preg_replace in your case given above.
Here is a simple solution that doesn't use a regex. It will ONLY replace single occurances of 'word' where it is a lone word.
<?php
$text = "word\word word cat dog";
$new_text = "";
$words = explode(" ",$text); // split the string into seperate 'words'
$inc = 0; // loop counter
foreach($words as $word){
if($word == "word"){ // if the current word in the array of words matches the criteria, replace it
$words[$inc] = "***";
}
$new_text.= $words[$inc]." ";
$inc ++;
}
echo $new_text; // gives 'word\word *** cat dog'
?>

Regex for breaking repeated characters

I have a comment box on my site , what I want here is if a user writes input (any character) which is more than 20 characters and doesnot put space between them then it should place a space between it.
Like: "asdasdasdasdasdasdasdasd"
Parsed: "asdasdasdasdasdasdas dasd"
I think it can be done with string compare but I want the regex to match it or the full solution. Thanks for any help.
it is called word wrapping.
http://php.net/manual/en/function.wordwrap.php
from examples :
<?php
$text = "A very long woooooooooooord.";
$newtext = wordwrap($text, 8, " ", true);
echo "$newtext\n";
?>
output:
A very long wooooooo ooooord.
The function wordwrap does this job well. But here is a regex based solution:
$str = "asdasdasdasdasdasdasdasd";
$str = preg_replace('/(.{20})/','$1 ',$str);
This will put add a space even if the input is of size 20. If you don't want that use:
$str = preg_replace('/(.{20})(?=.)/','$1 ',$str);

Categories