Adding a custom field to a slug

Try to use function sanitize_title()documentation, which converts a string into a slug when you check if it is already in the permalink, and when appending it to permalink:

function custom_job_post_type_link( $post_id, $post ) {

    $permalink = $post->post_name;  
    $companyname = $post->_company_name;

    if ( strpos( $permalink, sanitize_title($companyname) ) ) { // <-- Here
        return;
    }
    
    // unhook this function to prevent infinite looping
    remove_action( 'save_post_job_listing', 'custom_job_post_type_link', 10, 2 );

    // add the id to the slug
    $permalink .= '-' . sanitize_title($companyname); // <-- And here

    // update the post slug
    wp_update_post( array(
        'ID' => $post_id,
        'post_name' => $permalink
    ));

    // re-hook this function
    add_action( 'save_post_job_listing', 'custom_job_post_type_link', 10, 2 );
}

add_action( 'save_post_job_listing', 'custom_job_post_type_link', 10, 2 );

error code: 521