How to wrap words of string every 1000 characters in php - php

i have some big string, and some array of words that must be replaced with some changes, like wrapping in link. First issue is wrap whole words or combinations words. And the second issue is do previous step minimum every 1000 characters.
$string="lalala word lalala blah, blah lalala combination of words lalala lalala...";
$patterns=array('word','combination of words');
$replacements=array('word','combination of words');
For an example, what i must to do with snippet before?

It sounds to me like you're looking for wordwrap(). You can then use preg_replace_callback() to apply it to your search patterns and make the replacements:
foreach ($patterns as $pattern) {
$regex = '/' . preg_quote($pattern, '/') . '/';
$string = preg_replace_callback($regex, function($match) {
return '<a href="#">'
. wordwrap(htmlspecialchars($match), 1000, '<br />')
. '</a>';
}, $string);
}

SOLUTION:
<?php
function set_keys_by_words($content, $key, $words,$before,$after) {
$positions = array();
$string = '';
for ($i = 0; $i < count($words); $i++) {
$string = preg_replace('/\b' . $words[$i] . '\b/ui', $key . $words[$i], $content);
$position = mb_strpos($string, $key);
if ($position != '') {
$positions[(int) $position] = $words[$i];
}
}
ksort($positions);
$word = '';
$number = '';
$i = 0;
foreach ($positions as $k => $v) {
$i++;
if ($i == 1) {
$number = $k;
$word = $v;
}
}
if ((int) $number) {
$word_len = strlen($word);
$part_after = preg_replace('/\b' . $word . '\b/ui', $before . $word . $after, mb_substr($content, 0, $number + $word_len));
echo $part_after . mb_substr($content, $number + $word_len, 1000);
$content = mb_substr($content, $number + $word_len + 1000);
if ($content != '') {
set_keys_by_words($content, $key, $words);
}
} else if ($number == '' && $content != '') {
echo $content;
}
}
?>

Related

make first letter caps in php but ucfirst(strtolower('string')) does not work

I've been trying to make the first letter of a string in the capital but I can't get it to work.
I have tried the following code:
<?php
$str = $_POST['Papier'];
$f = highlightKeywords('papierwaren', $str);
$s = strtolower($f);
$r = ucfirst($s);
function highlightKeywords($text, $keyword)
{
$pos = strpos($text, $keyword);
$wordsAry = explode(" ", $keyword);
$wordsCount = count($wordsAry);
for ($i = 0; $i < $wordsCount; $i++) {
if ($pos === false) {
$highlighted_text = "<span style='font-weight:700;color:#151313;'>" . strtolower($wordsAry[$i]) . "</span>";
} else {
$highlighted_text = "<span style='font-weight:700;color:#151313;'>" . $wordsAry[$i] . "</span>";
}
$text = str_ireplace($wordsAry[$i], $highlighted_text, $text);
}
return $text;
}
still, I am not getting it to work and I tried if whitespace occurs with the following
$r=ucfirst(trim($s));
still not succeeded. This 'papierwaren' text i'm getting it form db so pls someone help me to resolve this.
As Kaddath said, You are adding HTML to your string (<span ...). When you use ucfirst it changes the first char to uppercase but the first char is now <, the uppercase for < is <.
Try this code:
<?php
$str = 'papier';
$f = highlightKeywords('papierwaren', $str);
echo $f;
function highlightKeywords($text, $keyword)
{
$pos = strpos($text, $keyword);
$wordsAry = explode(" ", $keyword);
$wordsCount = count($wordsAry);
for ($i = 0; $i < $wordsCount; $i++) {
if ($pos === false) {
if ($i === 0) {
$highlighted_text = "<span style='font-weight:700;color:#151313;'>" . ucfirst(strtolower($wordsAry[$i])) . "</span>";
} else {
$highlighted_text = "<span style='font-weight:700;color:#151313;'>" . strtolower($wordsAry[$i]) . "</span>";
}
} else {
if ($i === 0) {
$highlighted_text = "<span style='font-weight:700;color:#151313;'>" . ucfirst($wordsAry[$i]) . "</span>";
} else {
$highlighted_text = "<span style='font-weight:700;color:#151313;'>" . $wordsAry[$i] . "</span>";
}
}
$text = str_ireplace($wordsAry[$i], $highlighted_text, $text);
}
return $text;
}
In laravel this should help
use Illuminate\Support\Str;
$testString = 'this is a sentence.';
$uppercased = Str::ucfirst($testString);
Do not forget to import Illuminate\Support\Str to controller.

Adding custom masks to phone numbers

So i'm creating a simple function to mask phone numbers. My phone numbers have a 9 digits and i want preg_replace them with a given mask like 2-2-2-1-2 or 3-2-2-2 and etc.
I tried this:
$mask = explode('-', '3-2-2-2');
$pattern = '';
$replace = '';
foreach ($mask as $key => $value) {
if ($key == 0) {
$pattern = '/\(?(\d{' . $value . '})\)?[- ]';
$replace = '$' . ++$key . '-';
continue;
}
if ($key == count($mask) - 1) {
$pattern .= '?(\d{' . $value . '})/';
$replace .= '$' . ++$key;
break;
}
$pattern .= '?(\d{' . $value . '})[- ]';
$replace .= '$' . ++$key . '-';
}
return preg_replace($pattern, $replace, '902000810');
and the result is 902-00-08-10. Sometimes getting error preg_replace(): No ending delimiter '/' found. How can i refactor this to not getting errors?
Assuming:
$num = '902000810';
$mask = explode('-', '3-2-2-2');
There're other ways than using regex to format a phone number from the mask.
using formatted strings:
$maskPH = array_map(fn($i) => "%{$i}s", $mask);
$formatI = implode('', $maskPH);
$formatO = implode('-', $maskPH);
$result = vsprintf($formatO, sscanf($num, $formatI));
using unpack:
$format = array_reduce($mask, function ($c, $i) {
static $j = 0;
return "{$c}A{$i}_" . $j++ . "/";
});
$result = implode('-', unpack($format, $num));
preg_replace(): No ending delimiter '/' found
means that your pattern does not terminate with a / as last character.
But all three patterns lack proper formatting:
You should modify them accordingly.
From:
$pattern = '/\(?(\d{' . $value . '})\)?[- ]';
$pattern .= '?(\d{' . $value . '})/';
$pattern .= '?(\d{' . $value . '})[- ]';
To:
$pattern = '/\(?(\d{' . $value . '})\)?[- ]/';
$pattern .= '/?(\d{' . $value . '})/';
$pattern .= '/?(\d{' . $value . '})[- ]/';

Explode Hyphens in breadcrumbs

I have this script that does nearly exactly what I would like it to do but I need to remove the hyphens.
It produces the breadcrumbs using the pages of my website but I need it to do this
Home > Aaa bbb ccc > Aaa bbb
instead of
Home > Aaa-bbb-ccc > Aaa-bbb
I know I need to use the PHP explode() function but I cannot seem to figure out where the put it.
<?php
function breadcrumbs($separator = ' > ', $home = 'Home') {
$path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
$base_url = substr($_SERVER['SERVER_PROTOCOL'], 0, strpos($_SERVER['SERVER_PROTOCOL'], '/')) . '://' . $_SERVER['HTTP_HOST'] . '/';
$breadcrumbs = array("$home");
$tmp = array_keys($path);
$last = end($tmp);
unset($tmp);
foreach ($path as $x => $crumb) {
$title = ucwords(str_replace(array('.php', '_'), array('', ' '), $crumb));
if ($x == 1){
$breadcrumbs[] = "$title";
}elseif ($x > 1 && $x < $last){
$tmp = "<a href=\"$base_url";
for($i = 1; $i <= $x; $i++){
$tmp .= $path[$i] . '/';
}
$tmp .= "\">$title</a>";
$breadcrumbs[] = $tmp;
unset($tmp);
}else{
$breadcrumbs[] = "$title";
}
}
return implode($separator, $breadcrumbs);
}
echo breadcrumbs();
?>
Just expand what you have to:
$title = ucwords(str_replace(array('.php', '_', '-'), array('', ' ', ' '), $crumb));

How to style a character in a string at specific index?

Would you please give me some guidance on how to style one character in a string at specific index? the index of this string comes from an array and in some cases the array is empty, so I only need to style the character in the string if the array is not empty
$indices = array(74, 266);
$string = "CAGGACACTCTTTCTAGTGTTGATTCACCTCGAAGAAGGTCTGGCCTATTAAGAGATCAAGTTCAGTTGGTAAAAAGAAGCAACTCTGCTCGTTATGAGATAGTCCCGATTCAAGATCAACTATCATTTGAGAAGGGTTTCTTTATTGTAATCCGTGCATGCCAGTTGTTGGCTCAGAAGAATGAAGGCATTGTACTGGTGGGAGTCGCTGGTCCTTCAGGGGCCGGAAAGACCATGTTTACAGAAAAGATCCTGAATGTTATGCCTAGTATTGCAATCATAAACATGGACAACTACAATGATCCCAGTCGTATCATTGATGGAAACTTCGACG";
so how do I add a surround the character at the index 74 and 266 with a span so I can give it a different style?
my data is coming from the database so I need to make it dynamic.
Thanks
It's fairly easy: all you need is a few substrs in a loop and to keep track of the character count.
Here's a working code I made:
// zero-based indices
$indices = array(3, 10, 25);
// input
$in = 'abcDefghijKlmnopqrstuvwxyZ';
$openTag = '<b>';
$closeTag = '</b>';
$out = '';
$last = 0;
foreach($indices as $i) {
$fragment = substr($in, $last, $i-$last);
$letter = substr($in, $i, 1);
$last = $i+1;
$out .= $fragment . $openTag . $letter . $closeTag;
}
$out .= substr($in, $last);
// output
echo $out;
For this example, $out is abc<b>D</b>efghij<b>K</b>lmnopqrstuvwxy<b>Z</b>.
For convenience, here's it also as a function:
function highlightChars($text, $indices, $openTag, $closeTag) {
$out = '';
$last = 0;
foreach($indices as $i) {
$fragment = substr($text, $last, $i-$last);
$letter = substr($text, $i, 1);
$last = $i+1;
$out .= $fragment . $openTag . $letter . $closeTag;
}
$out .= substr($text, $last);
return $out;
}

Explode and leave delimiter

This is my function:
$words = explode('. ',$desc);
$out = '';
foreach ($words as $key => $value) {
$out .= $value;
$rand = rand(0, 4);
if ($rand == 2) {
$out .= "\n";
} else {
$out .= ' ';
}
}
In short it's inserting new lines after random dots, but in this case dots are removed.
How could I do explode('. ',$desc), and leave dots in where they are?
Just put them back in when you concatenate.
$words = explode('. ',$desc);
$out = '';
foreach ($words as $key => $value) {
$out .= $value.'.';
$rand = mt_rand(0, 4);
if ($rand == 2) {
$out .= "\n";
} else {
$out .= ' ';
}
}
You should also use mt_rand(), it is a much better version of rand() unless you like not really random results.
Positive look behind without regex subject.
$words = preg_split('/(?<=\.)(?!\s*$)/', $desc);
Split at any non-character with a dot behind it.
Try this code..
$words = explode('. ',$desc);
$out = '';
foreach ($words as $key => $value) {
$out .= $value;
$rand = rand(0, 4);
if ($rand == 2) {
$out .= "<br>";
} else {
$out .= ' ';
}
}

Categories