Encode contents between Two Special Strings - php

All I want is to Get contents between two strings like the following line:
$content = '81Lhello82R 81Lmy82R 81Lwife82R';
I wish to get all contents between 81L and 82R, then encode them to Base64 automatically by Preg_match I think, I've done some ways to do it but didn't get what was expected!
Base Form:
81Lhello82R 81Lmy82R 81Lwife82R
Output:
81LaGVsbG8=82R 81LbXk=82R 81Ld2lmZQ==82R

Hard rules:
$leftMask = '81L';
$rightMask = '82R';
$content = '81Lhello82R 81Lmy82R 81Lwife82R';
preg_match_all('#'.$leftMask.'(.*)'.$rightMask.'#U',$content, $out);
$output = [];
foreach($out[1] as $val){
$output[] = $leftMask.base64_encode($val).$rightMask;
}
$result = str_replace($out[0], $output, $content);
RegExp rules
$leftMask = '\d{2}L';
$rightMask = '\d{2}R';
$content = '81Lhello82R 81Lmy82R 81Lwife82R';
preg_match_all('#('.$leftMask.')(.*)('.$rightMask.')#U',$content, $out);;
$output = [];
foreach($out[2] as $key=>$val){
$output[] = $out[1][$key].base64_encode($val).$out[3][$key];
}
$result = str_replace($out[0], $output, $content);

This is a job for preg_replace_callback:
$content = '81Lhello82R 81Lmy82R 81Lwife82R';
$output = preg_replace_callback(
'/(?<=\b\d\dL)(.+?)(?=\d\dR)/',
function($matches) {
return base64_encode($matches[1]); // encode the word and return it
},
$content);
echo $output,"\n";
Where
(?<=\b\d\dL) is a positive lookbehind that makes sure we have 2 digits and the letter L before the word to encode
(?=\d\dR) is a positive lookahead that makes sure we have 2 digits and the letter R after the word to encode
(.+?) is the capture group that contains the word to encode
Output:
81LaGVsbG8=82R 81LbXk=82R 81Ld2lmZQ==82R

Related

Split string with PHP piece by piece

I have a string that I want to split like this:
Sinn.und.Sinnlichkeit.1995.German.DL.1080p.BluRay.x264-RSG <--- Original string
Sinn.und.Sinnlichkeit.1995.German.DL.1080p.BluRay.x264 <--- no match
Sinn.und.Sinnlichkeit.1995.German.DL.1080p.BluRay <--- no match
Sinn.und.Sinnlichkeit.1995.German.DL.1080p <--- no match
Sinn.und.Sinnlichkeit.1995.German.DL <--- no match
Sinn.und.Sinnlichkeit.1995.German <--- no match
Sinn.und.Sinnlichkeit.1995 <--- no match
Sinn.und.Sinnlichkeit <--- match
Sinn.und <--- no match
Sinn <--- no match
Until it has a API match.
Can you help me with that? I tried with preg_split, but it's not really working...
$string = 'Sinn.und.Sinnlichkeit.1995.German.DL.1080p.BluRay.x264-RSG';
$split = preg_split('/[.-]/', $string);
foreach( $split AS $explode )
{
echo $explode;
}
You're splitting correct. All it takes is a for loop, building the required $arr from the parts as you go along.
$string = 'Sinn.und.Sinnlichkeit.1995.German.DL.1080p.BluRay.x264-RSG';
$split = preg_split('/[.-]/', $string);
$arr = [];
$brr = [];
foreach( $split AS $explode)
{
$arr[] = $explode;
// check $arr or implode($arr) with api
// or push to
$brr[] = $arr;
}
$result = array_reverse($brr);

Replace words and maintain case-sensitivity of the found string

I am creating a php application to format files. So I need to apply a find-replace process while maintaining the case.
For example, I need to replace 'employees' with 'vehicles'.
$file_content = "Employees are employees_category MyEmployees kitEMPLOYEESMATCH";
$f = 'employees';
$r = 'vehicles';
echo str_ireplace($f, $r, $file_content);
Current Output:
vehicles are vehicles_category Myvehicles kitvehiclesMATCH
Desired Output:
Vehicles are vehicles_category MyVehicles kitVEHICLESMATCH
You could use something like this by replacing for each case separately:
<?php
$file_content = "Employees are employees_category MyEmployees kitEMPLOYEESMATCH";
$f = 'employees';
$r = 'vehicles';
$res = str_replace($f, $r, $file_content); // replace for lower case
$res = str_replace(strtoupper($f), strtoupper($r), $res); // replace for upper case
$res = str_replace(ucwords($f), ucwords($r), $res); // replace for proper case (capital in first letter of word)
echo $res
?>
While the SJ11's answer is attractive for its brevity, it is prone to making unintended replacements on already replaced substrings -- though not possible with the OP's sample data.
To ensure that replacements are not replaced, you must make only one pass over the input string.
For utility, I will include preg_quote(), so that pattern does not break when the $r value contains characters with special meaning in regex.
Code: (Demo) (PHP7.4 Demo)
$file_content = "Employees are employees_category MyEmployees kitEMPLOYEESMATCH";
$f = 'employees';
$r = 'vehicles';
$pattern = '~('
. implode(
')|(',
[
preg_quote($f, '~'),
preg_quote(ucfirst($f), '~'),
preg_quote(strtoupper($f), '~')
]
) . ')~';
$lookup = [
1 => $r,
2 => ucfirst($r),
3 => strtoupper($r)
];
var_export(
preg_replace_callback(
$pattern,
function($m) use ($lookup) {
return $lookup[count($m) - 1];
},
$file_content
)
);
Output: (single quotes are from var_export())
'Vehicles are vehicles_category MyVehicles kitVEHICLESMATCH'

Preg_Replace for a big int fitting a certain pattern

Within a GIGANTIC string I am trying to clean into json. I encounter something like this that breaks the script (usually multiple times from the same source)
{
29646191: [bunchofjson]
}
is there a preg_replace I can do to replace all occurances of
{
stringofrandomlysizednumbers: [anything]
}
With
{
"string...numbers": [anything]
}
List of things that havent worked:
$output = preg_replace('/([^\\\])":([0-9]{10,})(,|})/', '$1":"$2"$3', $output);
$output = preg_replace('/("\w+"):(\d+)(.\d+)?/', '\\1:"\\2\\3"', $output);
$output = preg_replace('/("\w+"):(\d+)/', '\\1:"\\2"', $output);
$output = preg_replace('/(\d+):/', '"$1":', $output);
$output = preg_replace('/("\w+"):(\d+)(.\d+)?/', '\\1:"\\2\\3"', $output);
$output = preg_replace('/:\s*(\-?\d+(\.\d+)?([e|E][\-|\+]\d+)?)/', ': "$1"', $output);
$output = json_decode($output, true, 512, JSON_BIGINT_AS_STRING));
(I json decode into an associative array when done in an ideal case)
I am guessing, and have not checked my code, but try this.
$output = preg_replace('/^\s*[0-9]{10,}.*/', '"string...numbers": \[anything\]', $output);
(I'm not sure the \[ and \] are required. I don't think they are but I put them there just encase...
the preg_replace will replace any line that has any number of spaces, then 10 consecutive numberic characters.
Input is exactly like this?
{
29646191: [bunchofjson]
}
Output will be like this
{
"string...numbers": [anything]
}
I believe you are looking for this replacement:
$output = preg_replace('/(?<=\s)(\d+)(?=\s*:)/', '"$1"', $output);

How to explode a string with commas and recompose except the first one

I have a string like this [tubelist dijfisj, ijdsifjad, ajkdfksd, sdjfkdf] and I would like to separate them into two ###URL### and ###URL2###.
This is the code I got so far
function xyz_plugin_callback($match)
{
$tag_parts = explode(",", rtrim($match[0], "]"));
$output = YOUX_TARGET;
$output = str_replace("###URL###", $tag_parts[1], $output);
$output = str_replace("###URL2###", $tag_parts[2], $output);
}
$match is the variable that I'm passing in.
You can utilize regular expressions here.
So if you do something like:
$temp_match = trim($match[0], "[]");
$urls = array();
preg_match("/([\w\s]*),([\w\s]*),.*/", $temp_match, $urls);
$url1 = $urls[1];
$url2 = $urls[2];
// do your $output str_replace here.
finally, I got it working! Here is the working code.
$tag_parts1 = explode(" ", rtrim($match[0], "]"));
$tag_parts = explode(",",$tag_parts1[1],2);
the first line will strip the [tubelist and ].
the second line with store the first set of value in array[0] and the rest to [1].
voila, case resolved.

Create acronym from a string containing only words

I'm looking for a way that I can extract the first letter of each word from an input field and place it into a variable.
Example: if the input field is "Stack-Overflow Questions Tags Users" then the output for the variable should be something like "SOQTU"
$s = 'Stack-Overflow Questions Tags Users';
echo preg_replace('/\b(\w)|./', '$1', $s);
the same as codaddict's but shorter
For unicode support, add the u modifier to regex: preg_replace('...../u',
Something like:
$s = 'Stack-Overflow Questions Tags Users';
if(preg_match_all('/\b(\w)/',strtoupper($s),$m)) {
$v = implode('',$m[1]); // $v is now SOQTU
}
I'm using the regex \b(\w) to match the word-char immediately following the word boundary.
EDIT:
To ensure all your Acronym char are uppercase, you can use strtoupper as shown.
Just to be completely different:
$input = 'Stack-Overflow Questions Tags Users';
$acronym = implode('',array_diff_assoc(str_split(ucwords($input)),str_split(strtolower($input))));
echo $acronym;
$initialism = preg_replace('/\b(\w)\w*\W*/', '\1', $string);
If they are separated by only space and not other things. This is how you can do it:
function acronym($longname)
{
$letters=array();
$words=explode(' ', $longname);
foreach($words as $word)
{
$word = (substr($word, 0, 1));
array_push($letters, $word);
}
$shortname = strtoupper(implode($letters));
return $shortname;
}
Regular expression matching as codaddict says above, or str_word_count() with 1 as the second parameter, which returns an array of found words. See the examples in the manual. Then you can get the first letter of each word any way you like, including substr($word, 0, 1)
The str_word_count() function might do what you are looking for:
$words = str_word_count ('Stack-Overflow Questions Tags Users', 1);
$result = "";
for ($i = 0; $i < count($words); ++$i)
$result .= $words[$i][0];
function initialism($str, $as_space = array('-'))
{
$str = str_replace($as_space, ' ', trim($str));
$ret = '';
foreach (explode(' ', $str) as $word) {
$ret .= strtoupper($word[0]);
}
return $ret;
}
$phrase = 'Stack-Overflow Questions IT Tags Users Meta Example';
echo initialism($phrase);
// SOQITTUME
$s = "Stack-Overflow Questions IT Tags Users Meta Example";
$sArr = explode(' ', ucwords(strtolower($s)));
$sAcr = "";
foreach ($sArr as $key) {
$firstAlphabet = substr($key, 0,1);
$sAcr = $sAcr.$firstAlphabet ;
}
using answer from #codaddict.
i also thought in a case where you have an abbreviated word as the word to be abbreviated e.g DPR and not Development Petroleum Resources, so such word will be on D as the abbreviated version which doesn't make much sense.
function AbbrWords($str,$amt){
$pst = substr($str,0,$amt);
$length = strlen($str);
if($length > $amt){
return $pst;
}else{
return $pst;
}
}
function AbbrSent($str,$amt){
if(preg_match_all('/\b(\w)/',strtoupper($str),$m)) {
$v = implode('',$m[1]); // $v is now SOQTU
if(strlen($v) < 2){
if(strlen($str) < 5){
return $str;
}else{
return AbbrWords($str,$amt);
}
}else{
return AbbrWords($v,$amt);
}
}
}
As an alternative to #user187291's preg_replace() pattern, here is the same functionality without needing a reference in the replacement string.
It works by matching the first occurring word characters, then forgetting it with \K, then it will match zero or more word characters, then it will match zero or more non-word characters. This will consume all of the unwanted characters and only leave the first occurring word characters. This is ideal because there is no need to implode an array of matches. The u modifier ensures that accented/multibyte characters are treated as whole characters by the regex engine.
Code: (Demo)
$tests = [
'Stack-Overflow Questions Tags Users',
'Stack Overflow Close Vote Reviewers',
'Jean-Claude Vandàmme'
];
var_export(
preg_replace('/\w\K\w*\W*/u', '', $tests)
);
Output:
array (
0 => 'SOQTU',
1 => 'SOCVR',
2 => 'JCV',
)

Categories