PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label str-replace. Show all posts
Showing posts with label str-replace. Show all posts

Sunday, November 20, 2022

[FIXED] How to get the names of a list of companies?

 November 20, 2022     php, preg-replace, regex, str-replace, string     No comments   

Issue

I want to create a function to simplify names of companies (e.g., Apple Inc., Microsoft Corporation, Advanced Micro Devices, Inc.) and create a lowercase string to embed in a URL (e.g., apple, microsoft, advanced-micro-devices).

function cleanCompany($companyName){
  $companyName= strtolower($companyName);
  $companyName=preg_replace('/(!||&||,||\.||\'||\"||\(||\))/i', '', $companyName);
  $companyName=str_replace(array('company',' corporation',', inc.',' inc.',' inc',' ltd.',' limited',' holding',' american depositary shares each representing one class a.',' american depositary shares each representing one class a',' american depositary shares each representing two',' american depositary shares each representing 2',' class a',' s.a.'), '', $companyName);
  $companyName=preg_replace('/(\s+)/i', '-', $companyName);
  return $companyName; 
}

Company names are in this link: https://iextrading.com/trading/eligible-symbols/

This function still has problems that I am trying to solve it with:

$companyName=str_replace(array('---','--'), array('-'), $companyName);

How do I improve this function or do this task?


Solution

Based on Barmar's advice, I modified the function, which works okay.

function slugCompany($c){
  $c= strtolower($c);
  $c=preg_replace('/[^\da-z\s]/i', '', $c);
  $c=str_replace(array('company',' corporation',', inc.',' inc.',' inc',' ltd.',' limited',' holding',' american depositary shares each representing one class a.',' american depositary shares each representing one class a',' american depositary shares each representing two',' american depositary shares each representing 2',' class a',' s.a.'), '', $c);
  $c=preg_replace('/(\s+)/i', '-', $c);
  return $c; 
}

Also, I added a loop to replace '--' to '-';

for ($i=0; $i < 5; $i++) { 
  if(strpos($c,'--')!==false){
    $c=str_replace('--','-', $c);
  }else{
    break;
  }
}

Another way, I tried

function slugCompany($c){
  $c= strtolower($c);
  $c=preg_replace('/[^\da-z\s]/i', '', $c);
  $words='11000th|american|and|a|beneficial|bond|b|class|common|company|corporation|corp|commodity|cumulative|co|c|daily|dep|depositary|depository|debentures|diversified|due|d|each|etf|equal|equity|exchange|e|financial|fund|fixedtofloating|fixed|floating|f|group|g|healthcare|holdings|holding|h|inc|incorporated|interests|interest|in|index|income|i|junior|j|k|liability|limited|lp|llc|ltd|long|l|markets|maturity|municipal|muni|monthly|m|noncumulative|notes|no|n|of|one|or|o|portfolio|pay|partnership|partner|par|perpetual|per|perp|pfd|preference|preferred|p|q|redeemable|repstg|representing|represents|rate|r|sa|smallcap|series|shs|shares|share|short|stock|subordinated|ser|senior|s|the|three|term|to|traded|trust|two|t|ultrashort|ultra|u|value|v|warrant|weight|w|x|y|z';
  $c=preg_replace('/\b('.$words.')\b/i', '', $c);
  $c=preg_replace('/(\s+)/i', '-', trim($c));
  return $c; 
}


Answered By - Emma
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to cut content before sentence?

 November 20, 2022     php, preg-replace, str-replace     No comments   

Issue

I have in my content a few paragraphs and want to cut everything before when I find for example: This is a comment statement

I tried with str_replace() but this is not possible with this method and with preg_replace but on every validation my content stay untouched.

Is there any better way to do so?


Solution

str_replace will not work in you case. Try preg_replace and remove the first matching pattern -

preg_replace('/.+?(?=This is a comment statement)/', '', $your_string, 1)

Detailed explanantion



Answered By - Sougata Bose
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I strip_tags except anchors with remote links?

 November 20, 2022     php, preg-replace, replace, str-replace, strip-tags     No comments   

Issue

How can I replace contents of a tag with it's link

$str = 'This <strong>string</strong> contains a <a href="/local/link.html">local link</a>
        and a <a href="http://remo.te/link.com">remote link</a>';
$str = strip_tags($str,'<a>'); // strip out the <strong> tag
$str = ?????? // how can I strip out the local link anchor tag, but leave the remote link?
echo $str;

Desired output:

This string contains a local link and a <a href="http://remo.te/link.com">remote link</a>

Or, better yet, replace contents of remote link with its url:

This string contains a local link and a http://remo.te/link.com

How can I achieve the final output?


Solution

To replace your remotely linked anchor with the URL:

<a href="(https?://[^"]+)">.*?</a>
$1

To remove the anchor around a local URL:

<a href="(?!https?://)[^"]+">(.*?)</a>
$1

Explanation:

Both expressions match <a href=", ">, and </a> literally. The first one will then match a remote URL (http, optional s, :// and everything up to the closing ") in a capture group that we can reference with $1. The second expression will match anything that does not start with the protocol used previously, and then capture the actual text of the link into $1.

Please note that regular expressions aren't the best solution to parsing HTML, since HTML is not a regular language. However, it seems like your use case is "simple" enough that we can make a regular expression. This will not work with links like <a href=''></a> or <a href="" title=""></a>, but it can be expanded on to allow for these use cases (hence my previous note of HTML not being regular).


PHP

$str = 'This <strong>string</strong> contains a <a href="/local/link.html">local link</a> and a <a href="http://remo.te/link.com">remote link</a>';
$str = strip_tags($str,'<a>');

$str = preg_replace('~<a href="(https?://[^"]+)".*?>.*?</a>~', '$1', $str);
$str = preg_replace('~<a href="(?!https?://)[^"]+">(.*?)</a>~', '$1', $str);

echo $str;
// This string contains a local link and a http://remo.te/link.com


Answered By - Sam
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to remove double slashes (\\r\\n\\r\\n) in str_replace

 November 20, 2022     php, preg-replace, replace, str-replace, wordpress     No comments   

Issue

I'm trying to remove <p> and </p> from my JSON rest API output. I did the below but the output it gives me has double slashes like \\r\\n\\r\\n. So how do I change the double slashes to single?

Here's my code

//Remove <p> HTML element and replace with line breaks
$return = str_replace('<p>', '', $return);
$return = str_replace('</p>', '\r\n\r\n', $return);
        
//Output the data in JSON format without escaping the URL slashes
wp_send_json($return, 200, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);

Or can the above me more efficient if I use preg_replace?


Solution

all is okay you Just need to use json_deocde in front side or where you want to print the result



Answered By - Salman ansari
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to remove multiple slashes in URI with 'PREG'

 November 20, 2022     php, preg-replace, str-replace     No comments   

Issue

I am using str_replace() for removing extra slashes from url i dont know how to redirect the url to new url if find multi slashes in url?

if(str_replace(':/','://', trim(preg_replace('/\/+/', '/', PERMALINK), '/')))
{
  echo 'Yes found multi slashes redirect it to new url';
}
else
{
  echo 'Not found multi slashes';
}

Solution

using the plus symbol + in regex means the occurrence of one or more of the previous character. So we can add it in a preg_replace to replace the occurrence of one or more / by just one of them

$url = "site.com/edition/new///";

$newUrl = preg_replace('/(/+)/','/',$url);

// now it should be replace with the correct single forward slash echo $newUrl



Answered By - Engr Moazam Haris
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, February 2, 2022

[FIXED] Replace extension on thumbnails

 February 02, 2022     php, str-replace, wordpress     No comments   

Issue

I'm trying to do something in wordpress, by default I'm using webp images, i succeeded using the_content filter on post pages, but not on featured images on home pages.

This is the code i use on post pages;

<?php 

add_filter('the_content', 'change_img', 99);
function change_img( $content )
{
    return str_replace('.webp', '.jpg', $content);
} ?>

This is the code i use to show featured images on homepage

<ul>

    <?php $ksf = new WP_Query( 'posts_per_page=8' ); ?>
  <?php while ($ksf -> have_posts()) : $ksf -> the_post(); ?>

            <li>
                <a href="<?php the_permalink() ?>">
            
<figure>
        <?php if( !empty(get_the_post_thumbnail()) ) {
    $feat_image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), "full", true);
    
    ?>
    <img  src="<?php echo (($feat_image[0]))?>" alt="<?php echo get_post_meta( get_post_thumbnail_id(), '_wp_attachment_image_alt', true ); ?>" width="750" height="422" />
    <?php  } ?>
    <figcaption>
        <?php the_title(); ?>
    </figcaption>
                </figure>   </a>    
            

            </li>
                        

        <?php endwhile;
wp_reset_postdata(); ?></ul>

Solution

Replace with this;

<?php 

add_filter('wp_get_attachment_image_src', 'change_img', 99);
function change_img( $image )
{
    return str_replace('.webp', '.jpg', $image);
} ?>

I tested it with the code you have.



Answered By - awakening
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing